package com.zhongshengnetwork.rightbe;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
//import android.support.annotation.NonNull;
//import android.support.v4.app.ActivityCompat;
//import android.support.v4.content.ContextCompat;
//import android.support.v4.view.ViewPager;
//import android.support.v4.app.Fragment;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.hys.utils.ImageUtils;
import com.wangnan.library.GestureLockView;
import com.wangnan.library.listener.OnGestureLockListener;
import com.wangnan.library.model.Point;
import com.wangnan.library.painter.AliPayPainter;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.Filter.FilterTools;
import com.zhongshengnetwork.rightbe.common.JsonMap;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.QiniuCallBack;
import com.zhongshengnetwork.rightbe.common.QiniuUploadModel;
import com.zhongshengnetwork.rightbe.common.StatusbarUtils;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.topgrid.activity.TopGridActivity;
import com.zhongshengnetwork.rightbe.dbmodel.LangPublishdbModel;
import com.zhongshengnetwork.rightbe.dbservice.LangPublishService;
import com.zhongshengnetwork.rightbe.gsonmodel.BindInfoModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangInfoModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangTypeModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LifeResultModel;
import com.zhongshengnetwork.rightbe.gsonmodel.PublicHomeMenuModel;
import com.zhongshengnetwork.rightbe.gsonmodel.QiniuModel;
import com.zhongshengnetwork.rightbe.gsonmodel.UserHomeMenuModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WeiShuInfoDetailModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WeiShuLabelInfoModel;
import com.zhongshengnetwork.rightbe.imageviewer.widget.ImageViewer;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;
import com.thinkcool.circletextimageview.CircleTextImageView;
import com.zhongshengnetwork.rightbe.Adv.activity.SplashActivity;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.Constant.LetterConstant;
import com.zhongshengnetwork.rightbe.Constant.WeiBoConstant;
import com.zhongshengnetwork.rightbe.common.AppUtils;
import com.zhongshengnetwork.rightbe.common.Base64;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.DeviceUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.HandlerDefine;
import com.zhongshengnetwork.rightbe.common.RCCommandUtils;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.activity.AppQRCodeActivity;
import com.zhongshengnetwork.rightbe.common.activity.MyBaseFragmentActivity;
import com.zhongshengnetwork.rightbe.common.activity.MyWebActivity;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.dialog.PayDialog;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.dbservice.LetterdbService;
import com.zhongshengnetwork.rightbe.dbservice.LogindbService;
import com.zhongshengnetwork.rightbe.dbservice.NotifydbService;
import com.zhongshengnetwork.rightbe.game.activity.PrePKActivity;
import com.zhongshengnetwork.rightbe.gsonmodel.AdvModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangFirstTypeModel;
import com.zhongshengnetwork.rightbe.gsonmodel.UserMsgInfoModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.ChannelHomeActivity;
import com.zhongshengnetwork.rightbe.lang.activity.CommonLangActivity;
import com.zhongshengnetwork.rightbe.lang.activity.LangDetailActivity;
import com.zhongshengnetwork.rightbe.lang.activity.LangPublishActivity;
import com.zhongshengnetwork.rightbe.lang.activity.LangSearchActivity;
import com.zhongshengnetwork.rightbe.lang.view.FindFragment;
import com.zhongshengnetwork.rightbe.lang.view.FindHomeFragment;
import com.zhongshengnetwork.rightbe.lang.view.HomeFragment;
import com.zhongshengnetwork.rightbe.lang.view.HomeLangFragment;
import com.zhongshengnetwork.rightbe.lang.view.MeFragment;
import com.zhongshengnetwork.rightbe.lang.view.MessageFragment;
import com.zhongshengnetwork.rightbe.lang.view.MsgHomeFragment;
import com.zhongshengnetwork.rightbe.lang.view.OneWordsFragment;
import com.zhongshengnetwork.rightbe.lang.view.SimpleFindFragment;
import com.zhongshengnetwork.rightbe.lang.view.SimpleHomeFragment;
import com.zhongshengnetwork.rightbe.lang.view.SimpleHomePageFragment;
import com.zhongshengnetwork.rightbe.login.BDThirdActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.my.activity.SettingsActivity;
import com.zhongshengnetwork.rightbe.qrcode.android.CaptureActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTPublishActivity;
import com.zhongshengnetwork.rightbe.wzt.model.WZTUtils;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import cn.jpush.android.api.JPushInterface;


public class MainActivity extends MyBaseFragmentActivity implements View.OnClickListener, PayDialog.NetEvevt,WbShareCallback {

    //底部和顶部栏目相关
    private ViewPager tabbar_fpview;
    private LinearLayout linear_game, linear_lang, linear_message,linear_my;
    private ImageButton img_game, img_lang, img_message, img_my;
    private TextView text_game, text_lang, text_message, text_my;
    public CircleTextImageView img_message_count;
    private CircleTextImageView img_my_count;
    private RelativeLayout tabbar_top_layout;
    private RelativeLayout tabbar_bottom_layout;
    private LinearLayout tabbar_bottom_line;
    private TextView topTitleTextView;
    private TextView topRightTextView;
    private ImageView topLeftImageView;
    private ImageView tabbar_top_icon;
    private int currentSelectIndex = 0;
    private List<Fragment> fragments;

    //图片浏览
    public ImageViewer imagePreivew;

    //对战码输入
    public static PayDialog.NetEvevt evevt;
    public MyHandler myHandler;

    //Activity请求码
    private static final int REQUEST_CODE_SCAN = 0x5001;
    public static final int REQUEST_PUBLISH = 1002;
    private static final int WZT_PUBLISH = 1003;
    public static final int REQUEST_PERMISSION = 2222;
    public static final int REQ_QR_CODE = 11002; // // 打开扫描界面请求码
    public static final int REQ_PERM_CAMERA = 11003; // 打开摄像头
    public static final int REQ_PERM_EXTERNAL_STORAGE = 11004; // 读写文件
    public static final int REQUEST_HOME_MENU = 11005; //微句自定义菜单
    public static final int REQUEST_WZT_MENU = 11006; //微纸条频道选择

    private HomeFragment homeFragment = null;
    private SimpleHomePageFragment simpleHomePageFragment = null;
    //private SimpleHomeFragment simpleHomeFragment = null;
    private FindHomeFragment findHomeFragment = null;
    private SimpleFindFragment simpleFindFragment = null;
    //private OneWordsFragment oneWordsFragment = null;
    //private FindFragment findFragment;
    //private MessageFragment messageFragment;
    private MsgHomeFragment msgHomeFragment;
    private MeFragment meFragment;

    private float density = 0;
    private int wztId = 0;

    private boolean mReceiverTag = false;   //广播接受者标识
    private static boolean isGettingUnRead = false;

    private long firstTime = 0;

    private String readNotify = "";
    private String signtext = "";
    List<String> moreList = null;
    private ClipboardManager myClipboard;

    //private GifImageView startgif;
    private int nowtime;

    private FrameLayout gesture_layout;
    private GestureLockView mGuestureLockView;
    private ImageView glv_header;
    private TextView glv_title;
    private TextView glv_tip;

    private LifeResultModel lifeResultModel = null;

    //后台发布相关
    private boolean isUploading = false; //是否正在发布图片
    private boolean isDealWithImg = false;//是否正在处理图片
    private boolean isPublishing = false; //是否正在发布
    private boolean isGettingQiNiuToken = false;
    private int imgIndex = 0;
    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private Handler mHandler = null;
    private boolean timerFlag = false;
    private static int delay = 100;
    private static int period = 100;  //0.1s
    private ArrayList<String> dragImages;//压缩长宽后图片
    private String imgString = "";
    private LangPublishdbModel langPublishdbModel = null;
    private QiniuModel qiniuModel = null;

    //首次协议相关
    private LinearLayout main_layout;
    private RelativeLayout first_load_layout;
    private ImageView agree_bg;
    private ImageView agree_img;
    private TextView a_title;
    private TextView p_title;
    private TextView c_title;
    private Button test_button;
    private Button login_button;
    private boolean isAgree = false;
    private boolean isShowTip = false;

    private void showTip(){//提示语修改：在你未阅读并勾选同意《用户协议》和《隐私政策》之前，仅能进行部分内容浏览，你可以选择继续浏览或者退出。

        final CustomDialog.Builder builder = new CustomDialog.Builder(MainActivity.this);
        builder.setTitle("用户协议和隐私政策");
        builder.setMessage("微句（以下简称 \"我们\"）深知个人信息对您的重要性，并会尽全力保护您的个人信息安全可靠。我们致力于维护您对我们的信任，恪守以下原则：权责一致原则、目的明确原则、选择同意原则、最少够用原则、确保安全原则、主体参与原则、公开透明原则等。同时，我们承诺，我们将按业界成熟的安全标准，采取相应的安全保护措施来保护您的个人信息。请在使用我们的产品或服务前，仔细阅读并了解《用户协议》和《隐私政策》。如您同意，请点击同意开始接受我们的服务。");
        builder.setPositiveButton("同意", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                isAgree = true;
                agreeGo();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        CustomDialog dialog = builder.create();
        dialog.msgTextView.setText("微句（以下简称 \"我们\"）深知个人信息对您的重要性，并会尽全力保护您的个人信息安全可靠。我们致力于维护您对我们的信任，恪守以下原则：权责一致原则、目的明确原则、选择同意原则、最少够用原则、确保安全原则、主体参与原则、公开透明原则等。同时，我们承诺，我们将按业界成熟的安全标准，采取相应的安全保护措施来保护您的个人信息。请在使用我们的产品或服务前，仔细阅读并了解");
        SpannableString clickString = new SpannableString("《用户协议》");
        clickString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent webIntent = new Intent(MainActivity.this, MyWebActivity.class);
                webIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/weijuagreement.do");
                startActivity(webIntent);//用户协议
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.parseColor("#87cefa"));//设置颜色
            }
        }, 0, clickString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        dialog.msgTextView.append(clickString);
        dialog.msgTextView.append("和");
        SpannableString clickString2 = new SpannableString("《隐私政策》");
        clickString2.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent webIntent = new Intent(MainActivity.this, MyWebActivity.class);
                webIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/weijuprivacy.do");
                startActivity(webIntent);//隐私政策
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.parseColor("#87cefa")); //设置颜色
            }
        }, 0, clickString2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        dialog.msgTextView.append(clickString2);
        dialog.msgTextView.append(new SpannableString("。如您同意，请点击同意开始接受我们的服务。\n"));
        SpannableString clickString3 = new SpannableString("立即退出");
        clickString3.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                finish();
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.parseColor("#FC6E51")); //设置颜色
            }
        }, 0, clickString3.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        dialog.msgTextView.append(clickString3);
        dialog.msgTextView.setMovementMethod(LinkMovementMethod.getInstance());//开始响应点击事件
        dialog.show();
    }

    private void agreeGo(){
        if (isAgree == true){
            SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(AdvertUtils.FirstViewLoadFlag, false);
        }
        main_layout.setVisibility(View.VISIBLE);
        first_load_layout.setVisibility(View.GONE);
    }

    private void clickAgree(){
        if (isAgree == true){
            isAgree = false;
            agree_bg.setVisibility(View.VISIBLE);
            agree_img.setVisibility(View.INVISIBLE);
        }else {
            isAgree = true;
            agree_bg.setVisibility(View.INVISIBLE);
            agree_img.setVisibility(View.VISIBLE);
        }
    }

    private void shake(){
        Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);//加载动画资源文件
        a_title.startAnimation(shake);
        p_title.startAnimation(shake);
        c_title.startAnimation(shake);
    }

    private void firstLoadView(){
        main_layout = (LinearLayout) findViewById(R.id.main_layout);
        first_load_layout = (RelativeLayout) findViewById(R.id.first_load_layout);
        first_load_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
        boolean flag = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.FirstViewLoadFlag, true);
        if (CommonUtils.isLogin() == false && flag == true){
            first_load_layout.setVisibility(View.VISIBLE);

            RelativeLayout click_layout = (RelativeLayout) findViewById(R.id.click_layout);
            click_layout.setClickable(true);
            click_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    clickAgree();
                }
            });


            agree_bg = (ImageView) findViewById(R.id.agree_bg);
            agree_bg.setClickable(true);
            agree_bg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    clickAgree();
                }
            });

            agree_img = (ImageView) findViewById(R.id.agree_img);
            agree_img.setClickable(true);
            agree_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    clickAgree();
                }
            });

            a_title = (TextView) findViewById(R.id.a_title);
            a_title.setClickable(true);
            a_title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    clickAgree();
                }
            });

            p_title = (TextView) findViewById(R.id.p_title);
            p_title.setClickable(true);
            p_title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent webIntent = new Intent(MainActivity.this, MyWebActivity.class);
                    webIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/weijuagreement.do");
                    startActivity(webIntent);//用户协议
                }
            });

            c_title = (TextView) findViewById(R.id.c_title);
            c_title.setClickable(true);
            c_title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent webIntent = new Intent(MainActivity.this, MyWebActivity.class);
                    webIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/weijuprivacy.do");
                    startActivity(webIntent);//隐私政策
                }
            });

            test_button = (Button) findViewById(R.id.test_button);
            test_button.setBackgroundResource(AppThemeUtils.getInstance().getCommonButtonBg());
            test_button.setClickable(true);
            test_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isAgree == false){
                        showTip();
                    }else {
                        agreeGo();
                    }
                }
            });

            login_button = (Button) findViewById(R.id.login_button);
            login_button.setBackgroundResource(AppThemeUtils.getInstance().getLightGreenButtonBg());
            login_button.setClickable(true);
            login_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isAgree == true){
                        agreeGo();
                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                        intent.putExtra("isAgree", false);
                        startActivity(intent);
                    }else {
                        ToastUtil.show(MainActivity.this, "亲，请先阅读并勾选同意《用户协议》和《隐私政策》。");
                        shake();
                    }
                }
            });

            /*
            final CustomDialog.Builder builder = new CustomDialog.Builder(MainActivity.this);
            builder.setTitle("关于微句");
            builder.setMessage("「微句」是什么？一句不简单的话，一句创意共鸣的话，一句关于「 生活」经历和「 人生」体会的话。或源于看了一部电影、看了一本书、看到了一句话、听了一首歌、经历了一件事、想到了一个点子、领悟到了一个道理，或展现独特见解，或表达人生感悟，或书写生活的喜闻乐见，或分享幽默诙谐~~~\n" +
                    "\n「微句」的初衷是从「 一句话」开始，让阅读和创作成为每个人每天习惯做的事。我们不输在起点，每天早晚坚持5分钟，读书写作会成为你自然而然去做的事。");
            builder.setPositiveButton("了解更多", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Intent wIntent = new Intent(MainActivity.this, MyWebActivity.class);
                    wIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/note.do");
                    startActivity(wIntent);
                }
            });
            builder.setNegativeButton("我知道了", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            CustomDialog dialog = builder.create();
            dialog.show();
            */

        }else {
            main_layout.setVisibility(View.VISIBLE);
            first_load_layout.setVisibility(View.GONE);
        }
    }

    private MyIUiListener mIUiListener = new MyIUiListener();
    class MyIUiListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            Log.e("TAG","分享成功~");
        }

        @Override
        public void onError(UiError uiError) {
            Log.e("TAG","分享出错~");
        }

        @Override
        public void onCancel() {
            Log.e("TAG","分享取消~");
        }

        @Override
        public void onWarning(int i) {

        }
    }

    class NiCaiFu360Painter extends AliPayPainter{
        @Override
        public void drawNormalPoint(Point point, Canvas canvas, Paint normalPaint) {
            super.drawNormalPoint(point, canvas, normalPaint);
        }

        @Override
        public void drawPressPoint(Point point, Canvas canvas, Paint pressPaint) {
            //1.绘制中心点
            pressPaint.setStyle(Paint.Style.FILL);
            canvas.drawCircle(point.x,point.y,point.radius/4.0f, pressPaint);
            //2.绘制边界圆
            pressPaint.setStyle(Paint.Style.STROKE);
            pressPaint.setStrokeWidth(6);
            canvas.drawCircle(point.x, point.y, getGestureLockView().getRadius(), pressPaint);
            //super.drawPressPoint(point, canvas, pressPaint);
        }

        @Override
        public void drawErrorPoint(Point point, Canvas canvas, Paint errorPaint) {
            //1，绘制中心点
            errorPaint.setStyle(Paint.Style.FILL);
            canvas.drawCircle(point.x, point.y, point.radius/4.0f, errorPaint);
            //2，绘制边界圆
            errorPaint.setStyle(Paint.Style.STROKE);
            errorPaint.setStrokeWidth(6);
            canvas.drawCircle(point.x, point.y, getGestureLockView().getRadius(), errorPaint);
            //super.drawErrorPoint(point, canvas, errorPaint);
        }
    }

    //横竖切换时会触发
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //配置透明状态栏
        //StatusbarUtils.enableTranslucentStatusbar(this);

        setContentView(R.layout.tabbar);

        firstLoadView();
        imagePreivew = (ImageViewer) findViewById(R.id.imagePreivew);
        InitView();

        gesture_layout = (FrameLayout) findViewById(R.id.gesture_layout);

        gesture_layout.setBackgroundColor(AppThemeUtils.getInstance().getThemeColor());

        mGuestureLockView = (GestureLockView) findViewById(R.id.glv);
        mGuestureLockView.setPainter(new NiCaiFu360Painter());
        mGuestureLockView.setGestureLockListener(new OnGestureLockListener() {
            @Override
            public void onStarted() {

            }

            @Override
            public void onProgress(String progress) {

            }

            @Override
            public void onComplete(String result) {
                Log.e("TAG","密码是："+result);
                String key = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(LetterConstant.GestureKey+CustomApplication.loginModel.getUid(), "");
                 if (CommonUtils.isEmpty(result)){
                     return;
                 }else if (key.equals(result)){
                     //ToastUtil.show(MainActivity.this, "解锁成功");
                     MainActivity.this.gesture_layout.setVisibility(View.GONE);
                 }else {
                     //ToastUtil.show(MainActivity.this, "解锁失败");
                     mGuestureLockView.showErrorStatus(600);
                 }
            }
        });
        if (CommonUtils.isLogin() == true){
            String key = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(LetterConstant.GestureKey+CustomApplication.loginModel.getUid(), "");
            if (!CommonUtils.isEmpty(key)){
                glv_header = (ImageView) findViewById(R.id.glv_header);
                Glide.with(MainActivity.this).load(CustomApplication.loginModel.getThumbheader()).transform(new CircleTransform(MainActivity.this)).dontAnimate().into(glv_header);

                glv_title = (TextView) findViewById(R.id.glv_title);
                //glv_title.setTextColor(AppThemeUtils.getInstance().getMainColor());
                int hour = CommonUtils.getHourOfDay();
                if (hour >= 3 && hour < 6){
                    glv_title.setText("凌晨，好好休息~");
                }else if (hour >= 6 && hour < 8){
                    glv_title.setText("早上好~");
                }else if (hour >=8 && hour < 11){
                    glv_title.setText("上午好~");
                }else if (hour >= 11 && hour < 13){
                    glv_title.setText("中午好~");
                }else if (hour >= 13 && hour < 17){
                    glv_title.setText("下午好~");
                }else if (hour >= 17 && hour < 19){
                    glv_title.setText("傍晚好，写写微句~");
                }else if (hour >= 19 && hour < 23){
                    glv_title.setText("晚上好，阅读好时光~");
                }else {
                    glv_title.setText("深夜了，好梦~");
                }

                glv_tip = (TextView) findViewById(R.id.glv_tip);
                glv_tip.setClickable(true);
                glv_tip.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                        intent.putExtra("isCancleGesture", true);
                        startActivity(intent);
                    }
                });
            }else {
                gesture_layout.setVisibility(View.GONE);
            }
        }else {
            gesture_layout.setVisibility(View.GONE);
        }

        myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
        myHandler = new MyHandler(MainActivity.this);
        evevt = this;
        initPublishHandler();
        density = ScreenUtils.getScreenDensity(MainActivity.this);
        //注册广播
        registerBoradcastReceiver();
        new Thread() {
            @Override
            public void run() {
                super.run();
                //初始化融云：2018年11月10日屏蔽
                //CustomApplication.customApplication.initRongIMClient();
                getThirdName();
                getLangName(true);
                getHomeMenu(false);
                //初始化极光
                //JPushInterface.init(getApplicationContext());
                //获取启动广告
                getAdv();
                //获取绑定信息
                getbindInfo();
                try {
                    LangPublishService.deleteAllData();
                    if (CommonUtils.isLogin() == true){
                        if (SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean("oldAllDbData",false) == false){
                            SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean("oldAllDbData",true);
                            NotifydbService.updateOldData(CustomApplication.loginModel.getUid());
                        }
                    }

                }catch (Exception e){

                }
                //微博初始化
                initWeiBo();
            }
        }.start();
        getUnReadMsg();
        goToUrl();

        /*
        String data = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.WZTUserLabelData,"");
        if (CommonUtils.isEmpty(data)){
            getUserLabel(true);
        }
        */

        getUserLabel(true);

        /*
        //测试小部件数据
        String c = SPManageUtils.getInstance(CustomApplication.mContext).getSPString("xbj", "");
        if (CommonUtils.isEmpty(c)){
            SPManageUtils.getInstance(CustomApplication.mContext).putSPString("xbj", "数据");
        }
        */

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mReceiverTag) {   //判断广播是否注册
            Log.e("TAG","MainActivity广播被注销");
            mReceiverTag = false;   //Tag值 赋值为false 表示该广播已被注销
            unregisterReceiver(mBroadcastReceiver);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if(CommonUtils.isLogin() == true){
            if (SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean("NewUIMode", false) == false){
                SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean("NewUIMode", true);
                String mode = "标准模式";
                if (CommonUtils.getUIMode() == AdvertUtils.UI_Simple_Mode){
                    mode = "个性模式";
                }
                CustomDialog dialog = null;
                final CustomDialog.Builder builder = new CustomDialog.Builder(MainActivity.this);
                builder.setTitle("温馨提示");
                builder.setMessage("亲，微句的界面设计分为个性模式和标准模式，你当前使用的是"+mode+"，你可以在我的设置里进行模式切换和字体大小调节哦~");
                builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog = builder.create();
                dialog.show();
            }
        }else {
            if (isShowTip == true){//只触发一次
                return;
            }
            isShowTip = true;
            boolean flag = SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.FirstViewLoadFlag, true);
            if (CommonUtils.isLogin() == false && flag == true){//展示隐私政策
                showTip();
            }
        }

    }

    private void getThirdName(){
        final HashMap<String, String> map = new HashMap<String, String>();
        if(CommonUtils.isLogin() == true){
            map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
        }
        String url = "miniapp/langappid/thirddatatype.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                Log.e("TAG","ThirdName="+data);
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.ThirdDataName,data);
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    private void getLangName(boolean isFirst){
        final HashMap<String, String> map = new HashMap<String, String>();
        if(CommonUtils.isLogin() == true){
            map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
        }
        String mobileid = DeviceUtils.getDeviceID();
        if (mobileid == null || mobileid.length() == 0){
            mobileid = "";
        }
        map.put("isFirst",isFirst+"");
        map.put("type","100");
        map.put("mobileid",mobileid);
        map.put("uimode",CommonUtils.getUIMode()+"");
        String url = "miniapp/langappid/getsearchtype.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.LangTypeName,data);
                    SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.NoNameKey,GsonTools.getNoname(data));
                    SPManageUtils.getInstance(CustomApplication.mContext).putSPString("typeselect",GsonTools.gettypeselect(data));
                    SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(AdvertUtils.NewMsgNotifyKey+CustomApplication.loginModel.getUid(), GsonTools.getunReadState(data));
                    if (CommonUtils.isLogin() == true){
                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.CommonTypeName+CustomApplication.loginModel.getUid(), GsonTools.getCommonLang(data));
                    }
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }


    //获取微句首页菜单
    private void getHomeMenu(boolean isUpdate){

        final String d = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.LangTypeName,"");
        if (CommonUtils.isEmpty(d)){
            return;
        }
        if (CommonUtils.isLogin() == true){
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    //微句
                    final HashMap<String, String> map = new HashMap<String, String>();
                    map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
                    map.put("dataType","0");
                    String url = "home/menu/user/get.do";
                    HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            CommonModel commonModel = GsonTools.getCommonModel(data);
                            if (commonModel.getFlag().equals("1")){

                                List<String> list = new ArrayList<String>();
                                List<LangTypeModel>l = GsonTools.getLangTypeModel(d);
                                HashMap<String, String> menu = new HashMap<String, String>();
                                if (l != null && l.size() > 0){
                                    for (int i = 0; i < l.size(); i++){
                                        LangTypeModel m = l.get(i);
                                        menu.put(""+m.getId(), m.getName());
                                    }
                                }

                                if (menu.containsKey("21") == false){
                                    menu.put("21","话题探索");
                                }

                                if (menu.containsKey("30") == false){
                                    menu.put("30", "生活分享");
                                }

                                if (menu.containsKey("44") == false){
                                    menu.put("44","心里话");
                                }

                                if (menu.containsKey("116") == false){
                                    menu.put("116","笔记");
                                }

                                if (menu.containsKey("117") == false){
                                    menu.put("117","优秀笔记");
                                }

                                PublicHomeMenuModel publicHomeMenuModel = GsonTools.getPublicHomeMenuModel(data);
                                if (publicHomeMenuModel != null){
                                    if (!CommonUtils.isEmpty(publicHomeMenuModel.getDataValue())){
                                        List<String> vlist = CommonUtils.stringToArrayList(publicHomeMenuModel.getDataValue());
                                        String value = "";
                                        String name = "";
                                        for (int i = 0; i < vlist.size(); i++){
                                            String n = menu.get(vlist.get(i));
                                            if (!CommonUtils.isEmpty(n)){
                                                if (name.length() > 0){
                                                    name += ",";
                                                    value += ",";
                                                }
                                                name += n;
                                                value += vlist.get(i);
                                            }
                                        }
                                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.NewChannelDataKey, value);
                                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.NewChannelNameDataKey, name);
                                    }else {
                                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.NewChannelDataKey, "");
                                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.NewChannelNameDataKey, "");
                                    }
                                }else {
                                    SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.NewChannelDataKey, "");
                                    SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.NewChannelNameDataKey, "");
                                }

                                UserHomeMenuModel homeMenuModel = GsonTools.getUserHomeMenuModel(data);
                                if (homeMenuModel != null){
                                    if (CommonUtils.isEmpty(homeMenuModel.getDataValue())){
                                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.MyChannelDataKey+CustomApplication.loginModel.getUid(), "");
                                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.MyChannelNameDataKey+CustomApplication.loginModel.getUid(), "");
                                    }else {
                                        List<String> vlist = CommonUtils.stringToArrayList(homeMenuModel.getDataValue());
                                        for (int i = 0; i < vlist.size(); i++){
                                            if (list.size() > 0 && list.contains(vlist.get(i))){

                                            }else {
                                                list.add(vlist.get(i));
                                            }
                                        }
                                        String value = "";
                                        String name = "";
                                        for (int i = 0; i < list.size(); i++){
                                            String n = menu.get(list.get(i));
                                            if (!CommonUtils.isEmpty(n)){
                                                if (name.length() > 0){
                                                    name += ",";
                                                    value += ",";
                                                }
                                                name += n;
                                                value += list.get(i);
                                            }
                                        }
                                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.MyChannelDataKey, value);
                                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.MyChannelNameDataKey, name);
                                    }
                                }else {
                                    SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.MyChannelDataKey+CustomApplication.loginModel.getUid(), "");
                                    SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.MyChannelNameDataKey+CustomApplication.loginModel.getUid(), "");
                                }

                            }
                        }

                        @Override
                        public void onError(String msg) {

                        }
                    });

                    String wztData = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.WZTUserLabelData,"");
                    if (CommonUtils.isEmpty(wztData)){
                        return;
                    }

                    //微纸条
                    final HashMap<String, String> wztmap = new HashMap<String, String>();
                    wztmap.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
                    wztmap.put("dataType","1");
                    String wzturl = "home/menu/user/get.do";
                    HttpsUtils.miniAppDo(wztmap, wzturl, new HttpCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            CommonModel commonModel = GsonTools.getCommonModel(data);
                            if (commonModel.getFlag().equals("1")){
                                List<WeiShuLabelInfoModel>l = GsonTools.getWeiShuLabelInfoModel(wztData);
                                if (l != null && l.size() > 0){
                                    HashMap<String, String> menu = new HashMap<String, String>();
                                    for (int i = 0; i < l.size(); i++){
                                        WeiShuLabelInfoModel m = l.get(i);
                                        menu.put(m.getId()+"", m.getLabelName());
                                    }

                                    PublicHomeMenuModel publicHomeMenuModel = GsonTools.getPublicHomeMenuModel(data);
                                    if (publicHomeMenuModel != null){
                                        if (!CommonUtils.isEmpty(publicHomeMenuModel.getDataValue())){
                                            List<String> vlist = CommonUtils.stringToArrayList(publicHomeMenuModel.getDataValue());
                                            String value = "";
                                            String name = "";
                                            for (int i = 0; i < vlist.size(); i++){
                                                String n = menu.get(vlist.get(i));
                                                if (!CommonUtils.isEmpty(n)){
                                                    if (name.length() > 0){
                                                        name += ",";
                                                        value += ",";
                                                    }
                                                    name += n;
                                                    value += vlist.get(i);
                                                }
                                            }
                                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.NewWZTChannelDataKey, value);
                                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.NewWZTChannelNameDataKey, name);
                                        }else {
                                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.NewWZTChannelDataKey, "");
                                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.NewWZTChannelNameDataKey, "");
                                        }
                                    }else {
                                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.NewWZTChannelDataKey, "");
                                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.NewWZTChannelNameDataKey, "");
                                    }

                                    UserHomeMenuModel homeMenuModel = GsonTools.getUserHomeMenuModel(data);
                                    if (homeMenuModel != null){
                                        if (CommonUtils.isEmpty(homeMenuModel.getDataValue())){
                                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.MyWZTChannelDataKey+CustomApplication.loginModel.getUid(), "");
                                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.MyWZTChannelNameDataKey+CustomApplication.loginModel.getUid(), "");
                                        }else {
                                            List<String> list = new ArrayList<String>();
                                            List<String> vlist = CommonUtils.stringToArrayList(homeMenuModel.getDataValue());
                                            for (int i = 0; i < vlist.size(); i++){
                                                if (list.size() > 0 && list.contains(vlist.get(i))){

                                                }else {
                                                    list.add(vlist.get(i));
                                                }
                                            }
                                            String value = "";
                                            String name = "";
                                            for (int i = 0; i < list.size(); i++){
                                                String n = menu.get(list.get(i));
                                                if (!CommonUtils.isEmpty(n)){
                                                    if (name.length() > 0){
                                                        name += ",";
                                                        value += ",";
                                                    }
                                                    name += n;
                                                    value += list.get(i);
                                                }
                                            }
                                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.MyWZTChannelDataKey, value);
                                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.MyWZTChannelNameDataKey, name);
                                        }
                                    }else {
                                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.MyWZTChannelDataKey+CustomApplication.loginModel.getUid(), "");
                                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.MyWZTChannelNameDataKey+CustomApplication.loginModel.getUid(), "");
                                    }

                                }
                            }
                        }

                        @Override
                        public void onError(String msg) {

                        }
                    });

                }

            }.start();
        }
    }

    //获取用户标签
    private void getUserLabel(boolean isFirst){
        new Thread(){
            @Override
            public void run() {
                super.run();
                final HashMap<String, String> map = new HashMap<String, String>();
                if(CommonUtils.isLogin() == true){
                    map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
                }
                String url = "weishu/user/label/list.do";
                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.WZTUserLabelData,data);
                        }
                    }

                    @Override
                    public void onError(String msg) {

                    }
                });
            }
        }.start();

    }

    //屏蔽返回键的代码:
    public boolean onKeyDown(int keyCode,KeyEvent event)
    {
        switch(keyCode)
        {
            case KeyEvent.KEYCODE_BACK:showQuitTip(); return true;
            /*
            case KeyEvent.KEYCODE_HOME:return true;
            case KeyEvent.KEYCODE_BACK:return true;
            case KeyEvent.KEYCODE_CALL:return true;
            case KeyEvent.KEYCODE_SYM: return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN: return true;
            case KeyEvent.KEYCODE_VOLUME_UP: return true;
            case KeyEvent.KEYCODE_STAR: return true;
            */
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showQuitTip(){
        /*
        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(MainActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage("是否要现在退出？");
        builder.setPositiveButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                //RongIMClient.getInstance().disconnect();
                //finish();
                Intent home = new Intent(Intent.ACTION_MAIN);
                home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                home.addCategory(Intent.CATEGORY_HOME);
                startActivity(home);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
        */

        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            Toast.makeText(MainActivity.this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
            firstTime = secondTime;
        } else{
            if (CommonUtils.isLogin() == true &&  LangPublishService.getAllPublishCount(CustomApplication.loginModel.getUid()) > 0){
                final CustomDialog.Builder builder = new CustomDialog.Builder(MainActivity.this);
                builder.setTitle("温馨提示");
                builder.setMessage("你有内容正在发布中，确定要退出吗？");
                builder.setPositiveButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        stopTimer();
                        finish();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                CustomDialog dialog = builder.create();
                dialog.show();
            }else {
                stopTimer();
                finish();
            }

            /*
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            */
        }

    }

    /**********************以下导航相关************************/
    // 初始化工作
    private void InitView() {
        currentSelectIndex = 0;
        // 初始化 tabs
        tabbar_fpview = (ViewPager) findViewById(R.id.tabbar_fpview);
        linear_game = (LinearLayout) findViewById(R.id.linear_game);
        linear_lang = (LinearLayout) findViewById(R.id.linear_lang);
        linear_message = (LinearLayout) findViewById(R.id.linner_message);
        linear_my = (LinearLayout) findViewById(R.id.linner_my);

        img_game = (ImageButton) findViewById(R.id.img_game);
        img_lang = (ImageButton) findViewById(R.id.img_lang);
        img_message = (ImageButton) findViewById(R.id.img_message);
        img_message_count = (CircleTextImageView) findViewById(R.id.img_message_count);
        img_my = (ImageButton) findViewById(R.id.img_my);
        text_game = (TextView) findViewById(R.id.text_game);
        text_lang = (TextView) findViewById(R.id.text_lang);
        text_message = (TextView) findViewById(R.id.text_message);
        text_my = (TextView) findViewById(R.id.text_my);
        img_my_count = (CircleTextImageView) findViewById(R.id.img_my_count);
        img_my_count.setVisibility(View.INVISIBLE);

        text_game.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        //text_lang.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        text_message.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        text_my.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());


        fragments = new ArrayList<Fragment>();

        if (CommonUtils.getUIMode() == AdvertUtils.UI_Simple_Mode){

//            oneWordsFragment = new OneWordsFragment();
//            fragments.add(oneWordsFragment);

            simpleHomePageFragment = new SimpleHomePageFragment();
            simpleHomePageFragment.mainActivity = MainActivity.this;
            fragments.add(simpleHomePageFragment);

            simpleFindFragment = new SimpleFindFragment();
            simpleFindFragment.mainActivity = MainActivity.this;
            fragments.add(simpleFindFragment);


        }else {
            homeFragment = new HomeFragment();
            homeFragment.mainActivity = MainActivity.this;
            fragments.add(homeFragment);

            findHomeFragment = new FindHomeFragment();
            fragments.add(findHomeFragment);

        }



        msgHomeFragment = new MsgHomeFragment();
        msgHomeFragment.mainActivity = MainActivity.this;
        fragments.add(msgHomeFragment);
        meFragment = new MeFragment();
        meFragment.mainActivity = MainActivity.this;
        fragments.add(meFragment);

        /**
         * 这里Activity 只有继承 FragmentActivity 的时候 ，才会 getSupportFragmentManager()
         */
        // 设置适配器
        FragmentViewPageAdapter fragmentViewPageAdapter = new FragmentViewPageAdapter(
                getSupportFragmentManager(), fragments);
        tabbar_fpview.setAdapter(fragmentViewPageAdapter);
        //给tabs 设置点击监听事件
        linear_game.setOnClickListener(this);
        linear_lang.setOnClickListener(this);
        linear_message.setOnClickListener(this);
        linear_my.setOnClickListener(this);
        //设置ViewPage 切换效果
        tabbar_fpview.setOnPageChangeListener(new vpOnChangeListener());

        tabbar_top_layout = (RelativeLayout)findViewById(R.id.tabbar_top_layout);
        if (AppThemeUtils.getInstance().getAppTheme() != AppThemeUtils.AppThemeConstant.NORMAL_APP_Theme){
            tabbar_top_layout.setBackgroundColor(AppThemeUtils.getInstance().getThemeColor());
            tabbar_bottom_layout = (RelativeLayout) findViewById(R.id.tabbar_bottom_layout);
            tabbar_bottom_layout.setBackgroundColor(AppThemeUtils.getInstance().getThemeColor());
            tabbar_bottom_line = (LinearLayout) findViewById(R.id.tabbar_bottom_line);
            tabbar_bottom_line.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        }
        if (CommonUtils.getUIMode() == AdvertUtils.UI_Simple_Mode){
            /*
            if (oneWordsFragment != null){
                tabbar_top_layout.setVisibility(View.VISIBLE);
            }else{
                tabbar_top_layout.setVisibility(View.GONE);
            }
            */
            tabbar_top_layout.setVisibility(View.GONE);
        }else {
            tabbar_top_layout.setVisibility(View.VISIBLE);
        }

        topTitleTextView = (TextView) findViewById(R.id.tabbar_top_title);
        topTitleTextView.setText("首页");
        topTitleTextView.setClickable(true);
        topTitleTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickTopbar();
            }
        });

        topRightTextView = (TextView) findViewById(R.id.tabbar_top_righttext);
        topRightTextView.setText("频道");
        topRightTextView.setClickable(true);
        topRightTextView.setVisibility(View.VISIBLE);
        topRightTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(MainActivity.this, TopGridActivity.class);
//                startActivity(intent);
                enterChannel();
            }
        });

        topLeftImageView = (ImageView) findViewById(R.id.tabbar_top_leftimage);
        /*
        //备注：加上这个后，vivo nex机型不兼容，导致图标无法展示
        ViewGroup.LayoutParams params = topLeftImageView.getLayoutParams();
        params.width = (int) (27*density);
        params.height = (int) (27*density);
        topLeftImageView.setLayoutParams(params);
        topLeftImageView.setVisibility(View.VISIBLE);
        */
        topLeftImageView.setClickable(true);
        topLeftImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (tabbar_fpview.getCurrentItem() == 2){
                    msgHomeFragment.showMenu(v);
                }else if (tabbar_fpview.getCurrentItem() == 3){
                    Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
                    startActivity(intent);
                }else if (tabbar_fpview.getCurrentItem() == 1){
                    Intent intent = new Intent(MainActivity.this, LangSearchActivity.class);
                    startActivity(intent);
                    new Thread(){
                        @Override
                        public void run() {
                            super.run();
                            getLangName(false);
                        }
                    }.start();
                }

            }
        });
        topLeftImageView.setVisibility(View.INVISIBLE);


        tabbar_top_icon = (ImageView) findViewById(R.id.tabbar_top_icon);
        tabbar_top_icon.setClickable(true);
        tabbar_top_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentSelectIndex == 1 || currentSelectIndex == 2){



                    /*
                    Intent intent = new Intent(MainActivity.this, ScannerActivity.class);
                    //intent.putExtra(com.example.qrcode.Constant.EXTRA_IS_ENABLE_SCAN_FROM_PIC,true);
                    intent.putExtra(com.example.qrcode.Constant.KEY_AUTO_FOCUS,true);
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                    */
                    startQrCode();

                }else {
                    Intent intent = new Intent(MainActivity.this, AppQRCodeActivity.class);
                    startActivity(intent);
                }

            }
        });


        if (CommonUtils.isLogin() == true){
            long count = NotifydbService.getUnReadCount(CustomApplication.loginModel.getUid());

            //这里有问题
            if(LetterdbService.getAllUnReadCount(CustomApplication.loginModel.getUid()) > 0){
                count += 1;
                msgHomeFragment.updateSXTip(1);
            }else {
                msgHomeFragment.updateSXTip(0);
            }

            if (count > 0){
                img_message_count.setVisibility(View.VISIBLE);
                img_message_count.setText(count+"");
            }else {
                img_message_count.setVisibility(View.INVISIBLE);
            }
        }else {
            img_message_count.setVisibility(View.INVISIBLE);
        }
        ResetTabsImg();
        SetTabsSelectedImg(0);

    }

    private void onClickTopbar(){
        Log.e("TAG","点击了顶部");
        if (currentSelectIndex == 0){
            //首页
            /*
            if (homeLangFragment != null){
                homeLangFragment.scrollToFirstData();
            }
            */


            if (homeFragment != null){
                homeFragment.scrollToFirstData();
            }

//            if (oneWordsFragment == null && simpleHomePageFragment != null){
//                simpleHomePageFragment.scrollToFirstData();
//            }

        }else if (currentSelectIndex == 1){

//            if (oneWordsFragment != null){
//                if (simpleHomePageFragment != null){
//                    simpleHomePageFragment.scrollToFirstData();
//                }
//            }else {
//                //发现
//                if (findHomeFragment != null){
//                    findHomeFragment.scrollToFirstData();
//                }
//
//                if (simpleFindFragment != null){
//                    simpleFindFragment.scrollToFirstData();
//                }
//            }

            //发现
            if (findHomeFragment != null){
                findHomeFragment.scrollToFirstData();
            }

            if (simpleFindFragment != null){
                simpleFindFragment.scrollToFirstData();
            }

        }else if (currentSelectIndex == 2){
            //消息
            if (msgHomeFragment != null){
                msgHomeFragment.goToTop();
            }
        }else if (currentSelectIndex == 3){
            //我的
            if (meFragment != null){
                meFragment.getFirstData();
            }
        }
    }

    // 开始扫码
    public void startQrCode() {

        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
            return;
        }
        PermissionUtils.showCamaraNote(MainActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if(flag){
                    if (PermissionUtils.cameraIsCanUse() == false){
                        // 申请相机权限
                        Log.e("TAG","申请相机权限");
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, REQ_PERM_CAMERA);
                        return;
                    }

                    // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED){
                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES},
                                    REQUEST_PERMISSION);
                            return;
                        }
                    }else if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        // 申请权限
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_PERM_EXTERNAL_STORAGE);
                        return;
                    }
                    // 二维码扫码
                    Intent scanIntent = new Intent(MainActivity.this,
                            CaptureActivity.class);
                    startActivityForResult(scanIntent, REQUEST_CODE_SCAN);
                }
            }
        });

    }


    //进入频道
    public void enterChannel(){
        List<String> titleList = new ArrayList<String>();
        List<String> typeList = new ArrayList<String>();
        titleList.add("推荐");
        typeList.add("10000");
        String data = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.LangTypeName,"");
        if (CommonUtils.isEmpty(data)){
            titleList.add("感悟");
            titleList.add("创意");
            titleList.add("情感");
            titleList.add("唯美");
            titleList.add("文学");
            titleList.add("哲理");
            titleList.add("正能量");
            titleList.add("幽默");
            titleList.add("分享");
            titleList.add("教育");
            titleList.add("交际");
            titleList.add("时尚");

            typeList.add("1");
            typeList.add("2");
            typeList.add("3");
            typeList.add("4");
            typeList.add("5");
            typeList.add("6");
            typeList.add("7");
            typeList.add("8");
            typeList.add("9");
            typeList.add("10");
            typeList.add("11");
            typeList.add("12");
        }else {
            List<LangFirstTypeModel> l = GsonTools.getLangFirstTypeModel(data);
            if (l != null && l.size() > 0){
                for (LangFirstTypeModel m : l){
                    typeList.add(m.getId()+"");
                    titleList.add(m.getName());
                }
            }
        }
        Intent intent = new Intent(MainActivity.this, ChannelHomeActivity.class);
        intent.putExtra("title",CommonUtils.listToString(titleList));
        intent.putExtra("type",CommonUtils.listToString(typeList));
        startActivity(intent);
    }

     /**
      * 实现滑动 切换 tabs
      * @author Gordon
      */
     class vpOnChangeListener extends ViewPager.SimpleOnPageChangeListener {

         @Override
         public void onPageSelected(int position) {
             if (CommonUtils.isLogin() == false){
                 if (position == 2 || position == 3){
                     position = currentSelectIndex;
                 }
             }
             currentSelectIndex = position;
             //设置 tab 背景
             ResetTabsImg();
             SetTabsSelectedImg(position);
             System.out.print("position="+position+"\n");
         }
     }

     @Override
     public void onClick(View v) {
         ResetTabsImg();
         switch (v.getId()) {
             case R.id.linear_lang:
                 if (currentSelectIndex == 0){
//                     if (oneWordsFragment != null){
//                         oneWordsFragment.getNewData(false);
//                     }else{
//                         if (homeFragment != null){
//                             homeFragment.getNewData();
//                         }
//                         if (simpleHomePageFragment != null){
//                             simpleHomePageFragment.getNewData();
//                         }
//                     }

                     if (homeFragment != null){
                         homeFragment.getNewData();
                     }
                     if (simpleHomePageFragment != null){
                         simpleHomePageFragment.getNewData();
                     }

                 }
                 SetTabsSelectedImg(0);
                 break;
             case R.id.linear_game:
//                 if (currentSelectIndex == 1 && oneWordsFragment != null){
//                     if (simpleHomePageFragment != null){
//                         simpleHomePageFragment.getNewData();
//                     }
//                 }
                 SetTabsSelectedImg(1);
                 break;
             case R.id.linner_message:
                 if (CommonUtils.isLogin() == false){
                     Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                     startActivity(intent);
                     SetTabsSelectedImg(currentSelectIndex);
                 }else {
                     if (currentSelectIndex != 2){
                         //5分钟读取一次未读消息
                         String regId = CommonUtils.formatString(SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.JPUSHRegistrationId,""));
                         if (CommonUtils.isEmpty(regId)){
                             int lastime = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.LastGetUnReadMsgTime,0);//获取上次获取未读消息的时间
                             if (lastime > 0 && ((int)(System.currentTimeMillis()/1000) - lastime) >= 30){
                                 getUnReadMsg();
                             }
                         }
                     }
                     SetTabsSelectedImg(2);
                 }
                 break;
             case R.id.linner_my:
                 if (CommonUtils.isLogin() == false){
                     Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                     startActivity(intent);
                     SetTabsSelectedImg(currentSelectIndex);
                 }else {
                     SetTabsSelectedImg(3);
                     if (meFragment != null){
                         meFragment.updateMyInfo();//更新个人信息
                     }
                 }
                 break;
         }

     }

     /**
      * (1)实现选中后的 tabs的img
      * (2)切换 viewpager item
      * @param i
      */
     private void SetTabsSelectedImg(int i) {
         currentSelectIndex = i;
         switch (i) {
             case 0:
                 if (CommonUtils.getUIMode() == AdvertUtils.UI_Simple_Mode){
//                     if (oneWordsFragment != null){
//                         tabbar_top_layout.setVisibility(View.VISIBLE);
//                     }else{
//                         tabbar_top_layout.setVisibility(View.GONE);
//                     }
                     tabbar_top_layout.setVisibility(View.GONE);
                 }else {
                     tabbar_top_layout.setVisibility(View.VISIBLE);
                 }
                 /*
                 if (oneWordsFragment != null){
                     img_lang.setImageResource(R.drawable.gengxinon);
                     text_message.setTextColor(getResources().getColor(R.color.commonColor));
                     topTitleTextView.setText("一句不简单的话");
                     topLeftImageView.setImageResource(R.drawable.more);
                     topLeftImageView.setVisibility(View.VISIBLE);
                     topRightTextView.setVisibility(View.INVISIBLE);
                     tabbar_top_icon.setImageResource(R.drawable.searchicon);
                 }else{
                     img_lang.setImageResource(R.drawable.home_press);
                     text_lang.setTextColor(getResources().getColor(R.color.commonColor));
                     topTitleTextView.setText("首页");
                     topLeftImageView.setImageResource(R.drawable.searchicon);
                     topLeftImageView.setVisibility(View.INVISIBLE);
                     topRightTextView.setVisibility(View.VISIBLE);
                     tabbar_top_icon.setImageResource(R.drawable.codetwo);
                 }
                 */
                 img_lang.setImageResource(R.drawable.home_press);
                 text_lang.setTextColor(getResources().getColor(R.color.commonColor));
                 topTitleTextView.setText("首页");
                 topLeftImageView.setImageResource(R.drawable.searchicon);
                 topLeftImageView.setVisibility(View.INVISIBLE);
                 topRightTextView.setVisibility(View.VISIBLE);
                 tabbar_top_icon.setImageResource(R.drawable.codetwo);

                 break;
             case 1:
                 if (CommonUtils.getUIMode() == AdvertUtils.UI_Simple_Mode){
                     tabbar_top_layout.setVisibility(View.GONE);
                 }else {
                     tabbar_top_layout.setVisibility(View.VISIBLE);
                 }
                 img_game.setImageResource(R.drawable.find_press);
                 text_game.setTextColor(getResources().getColor(R.color.commonColor));
                 topTitleTextView.setText("发现");
                 topLeftImageView.setImageResource(R.drawable.searchicon);
                 topLeftImageView.setVisibility(View.VISIBLE);
                 topRightTextView.setVisibility(View.INVISIBLE);
                 tabbar_top_icon.setImageResource(R.drawable.scan);
                 break;
             case 2:
                 tabbar_top_layout.setVisibility(View.VISIBLE);
                 img_message.setImageResource(R.drawable.message_press);
                 text_message.setTextColor(getResources().getColor(R.color.commonColor));
                 topTitleTextView.setText("消息");
                 topLeftImageView.setImageResource(R.drawable.more);
                 topLeftImageView.setVisibility(View.VISIBLE);
                 topRightTextView.setVisibility(View.INVISIBLE);
                 tabbar_top_icon.setImageResource(R.drawable.scan);
                 if (msgHomeFragment != null){
                     msgHomeFragment.selectUpate();
                 }
                 break;
             case 3:
                 tabbar_top_layout.setVisibility(View.VISIBLE);
                 img_my.setImageResource(R.drawable.me_press);
                 text_my.setTextColor(getResources().getColor(R.color.commonColor));
                 topTitleTextView.setText("我的");
                 topLeftImageView.setImageResource(R.drawable.settings);
                 topLeftImageView.setVisibility(View.VISIBLE);
                 topRightTextView.setVisibility(View.INVISIBLE);
                 if (meFragment != null){
                     meFragment.updateSignText();
                 }
                 tabbar_top_icon.setImageResource(R.drawable.codetwo);
                 break;
         }

         //切换 viewpage item
         tabbar_fpview.setCurrentItem(i);
         if (tabbar_fpview.getCurrentItem() == 2){
             SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(LetterConstant.InMessageKey, true);
         }else {
             SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(LetterConstant.InMessageKey, false);
             SPManageUtils.getInstance(CustomApplication.mContext).putSPString(LetterConstant.InChatKey,"");
         }
     }

     /**
      * 将 tabs 的 图片设置 默认颜色
      */
     private void ResetTabsImg() {
         // 重置tab 图片
         img_game.setImageResource(R.drawable.find);
//         if (oneWordsFragment != null){
//             img_lang.setImageResource(R.drawable.gengxinoff);
//         }else{
//             img_lang.setImageResource(R.drawable.home);
//         }
         img_lang.setImageResource(R.drawable.home);

         img_message.setImageResource(R.drawable.message);
         img_my.setImageResource(R.drawable.me);
         //
         text_game.setTextColor(AppThemeUtils.getInstance().getSmallTextColor());
         text_lang.setTextColor(AppThemeUtils.getInstance().getSmallTextColor());
         text_message.setTextColor(AppThemeUtils.getInstance().getSmallTextColor());
         text_my.setTextColor(AppThemeUtils.getInstance().getSmallTextColor());
     }

     public void onClickPublish(View view){
         Log.e("TAG","点击了发布");
         /*
         if (CommonUtils.isLogin() == false){
             Intent intent = new Intent(MainActivity.this, LoginActivity.class);
             startActivity(intent);
             return;
         }
         */

         /*
         //2023-09-14屏蔽的相册权限申请
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
             if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED){
                 ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES},
                         REQUEST_PERMISSION);
                 return;
             }
         }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                 && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
             ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                     REQUEST_PERMISSION);
             ToastUtil.show(MainActivity.this,"亲，请开启应用对SD卡的读写权限");
             return;
         }
         */

         /*
         if (bindMobile() == true){//需要绑定手机号
             return;
         }
         */

         /*
         Intent intent = new Intent(MainActivity.this, LangPublishActivity.class);
         startActivityForResult(intent, REQUEST_PUBLISH);
         new Thread(){
             @Override
             public void run() {
                 super.run();
                 getLangName(false);
             }
         }.start();
         */

         if (moreList == null){
             moreList = new ArrayList<String>();
             if (CommonUtils.isLogin() == true){
                 if (SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.whiteKey, false) == true){
                     moreList.add("新增内容");
                 }
             }
             moreList.add("微句");
             moreList.add("笔记");
             //moreList.add("心里话");
             //moreList.add("生活分享");
             //moreList.add("话题探索");
             moreList.add("微纸条");
         }
         ActionSheetDialog actionSheetDialog = new ActionSheetDialog(MainActivity.this)
                 .builder()
                 .setTitle("发布类型")
                 .setCancelable(false)
                 .setCanceledOnTouchOutside(true);
         for (String s : moreList){
             actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                 @Override
                 public void onClick(int which) {
                     if (which > 0){
                         String title = moreList.get(which-1);
                         if (title.equals("微句")){
                             Intent intent = new Intent(MainActivity.this, LangPublishActivity.class);
                             startActivityForResult(intent, REQUEST_PUBLISH);
                         }else if (title.equals("笔记")){
                             Intent intent = new Intent(MainActivity.this, LangPublishActivity.class);
                             intent.putExtra("titlename","笔记");
                             intent.putExtra("tipname","记录你的点点滴滴~");//分享生活的点点滴滴
                             startActivityForResult(intent, REQUEST_PUBLISH);
                         }else if (title.equals("心里话")){
                             Intent intent = new Intent(MainActivity.this, LangPublishActivity.class);
                             intent.putExtra("titlename","心里话");
                             intent.putExtra("tipname","分享你的心声");
                             startActivityForResult(intent, REQUEST_PUBLISH);
                         }else if (title.equals("生活分享")){
                             Intent intent = new Intent(MainActivity.this, LangPublishActivity.class);
                             intent.putExtra("titlename","生活分享");
                             intent.putExtra("tipname","分享新鲜事");//分享生活的点点滴滴
                             startActivityForResult(intent, REQUEST_PUBLISH);
                         }else if (title.equals("话题探索")){
                             Intent intent = new Intent(MainActivity.this, LangPublishActivity.class);
                             intent.putExtra("titlename","话题探索");
                             intent.putExtra("tipname","探索你想知道的");
                             startActivityForResult(intent, REQUEST_PUBLISH);
                         }else if (title.equals("微纸条")){
                             getUserLabel(false);
                             Intent intent = new Intent(MainActivity.this, WZTPublishActivity.class);
                             startActivityForResult(intent, WZT_PUBLISH);
                         }else if (title.equals("新增内容")){
                             Intent intent = new Intent(MainActivity.this, LangPublishActivity.class);
                             intent.putExtra("status", 5);
                             startActivityForResult(intent, REQUEST_PUBLISH);
                         }
                     }
                 }
             });
         }
         actionSheetDialog.show();
         new Thread(){
             @Override
             public void run() {
                 super.run();
                 getLangName(false);
             }
         }.start();

     }

    @Override
    public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQ_PERM_CAMERA){
            // 摄像头权限申请
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                 // 获得授权
                 startQrCode();
            } else {
                 // 被禁止授权
                 Toast.makeText(MainActivity.this, "请到权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
            }
        }else if (requestCode == REQ_PERM_EXTERNAL_STORAGE){
                  // 文件读写权限申请
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                   // 获得授权
                   startQrCode();
            } else {
                  // 被禁止授权
                  Toast.makeText(MainActivity.this, "请到权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
            }
        }else if (requestCode == REQUEST_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission granted.
                Intent intent = new Intent(MainActivity.this, LangPublishActivity.class);
                startActivityForResult(intent, REQUEST_PUBLISH);
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        getLangName(false);
                    }
                }.start();
            } else {
                // User refused to grant permission.
            }
        }
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("TAG","结果返回requestCode="+requestCode);

        /*
        //由于MainActivity继承了MyBaseFragmentActivity，这里就不用了，会自动传递
        if (requestCode == Constants.REQUEST_QQ_SHARE || requestCode == Constants.REQUEST_QZONE_SHARE || requestCode == Constants.REQUEST_OLD_SHARE) {
            Tencent.onActivityResultData(requestCode, resultCode, data, mIUiListener);//传递结果
        }
        */

        if (requestCode == REQUEST_PUBLISH && resultCode == RESULT_OK) {//发布成功

            Message msg = new Message();
            msg.obj = new String(HandlerDefine.publishnotifymsg);
            msg.what = 0;
            if (data != null){
                boolean isBacken = data.getBooleanExtra("isBacken", false);
                if (isBacken == true){
                    msg.what = 1;
                }
            }
            myHandler.sendMessage(msg);

            /*
            if (meFragment != null){
                ResetTabsImg();
                SetTabsSelectedImg(3);
                meFragment.updateMyLang();
            }
            if (data != null){
                boolean isBacken = data.getBooleanExtra("isBacken", false);
                if (isBacken == true){
                    //后台发布
                    startTimer();
                }
            }
            */

        }else if (requestCode == WZT_PUBLISH && resultCode == RESULT_OK){//微纸条发布
            if (meFragment != null){
                ResetTabsImg();
                SetTabsSelectedImg(3);
                meFragment.updateMyWZT();
                wztId = data.getIntExtra("id",0);
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.wztnotifymsg);
                myHandler.sendMessageDelayed(msg,500);
            }

        }else if(requestCode == REQUEST_HOME_MENU && resultCode == RESULT_OK){

            int classify = data.getIntExtra("classify", 0);

            if (classify == 2){
                if (simpleHomePageFragment != null){
                    simpleHomePageFragment.getLatestData();
                }
                return;
            }

            if (homeFragment != null){
                int selectType = data.getIntExtra("type", 0);
                boolean isSelect = data.getBooleanExtra("isSelect", false);
                homeFragment.addData(true, selectType, isSelect);
            }

            if (simpleFindFragment != null){
                int selectType = data.getIntExtra("type", 0);
                boolean isSelect = data.getBooleanExtra("isSelect", false);
                simpleFindFragment.addData(true, selectType, isSelect);
            }

        }else if(requestCode == REQUEST_WZT_MENU && resultCode == RESULT_OK){

            if (homeFragment != null){
                homeFragment.updateWZT();
            }

        } else if (resultCode == RESULT_OK){
            if (requestCode == REQUEST_CODE_SCAN) {
                // 扫描二维码/条码回传
                //System.out.print("扫描二维码/条码回传 \n");
                Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
                long [] pattern = {100,400};   // 停止 开启
                vibrator.vibrate(pattern,-1);           //重复两次上面的pattern 如果只想震动一次，index设为-1
                if (data != null) {
                    final String content = data.getStringExtra("codedContent");
                    System.out.print("解码结果:" + content+"\n");
                    if(content.contains("http") || content.contains("https")){

                        if (content.contains("qrcode.do") == true){
                            RCCommandUtils.dealWithQRCode(content,MainActivity.this);
                        }else if(content.contains("weishu/share.do") == true){
                            RCCommandUtils.dealWithWZTQRCode(content, MainActivity.this);
                        }else if (content.contains("classify/share.do") == true){
                            RCCommandUtils.dealWithClassifyQRCode(content, MainActivity.this);
                        }else {
                            Intent intent = new Intent(MainActivity.this,MyWebActivity.class);
                            intent.putExtra(APIKey.urlKey,content);
                            startActivity(intent);
                        }

                    }else {
                        if (!CommonUtils.isEmpty(content)){
                            CustomDialog dialog = null;
                            final CustomDialog.Builder builder = new CustomDialog.Builder(MainActivity.this);
                            builder.setTitle("扫描结果");
                            builder.setMessage(content);
                            builder.setPositiveButton("复制", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    onClickCopy(content);
                                }
                            });
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            dialog = builder.create();
                            dialog.show();
                        }
                    }

                }
            }
        }
    }

    private void onClickCopy(String text){
        if (myClipboard == null){
            return;
        }
        try{
            ClipData myClip = ClipData.newPlainText("text", text);
            myClipboard.setPrimaryClip(myClip);
            Toast.makeText(getApplicationContext(), "内容已复制~",
                    Toast.LENGTH_SHORT).show();
        }catch (Exception e){

        }
    }

    private void dealWithWZT(final String id, final int selectIndex){
         new Thread(new Runnable() {
             @Override
             public void run() {
                 final HashMap<String, String> map = new HashMap<String, String>();
                 map.put(APIKey.idKey, id);
                 if (CommonUtils.isLogin() == true){
                     map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
                 }
                 String url = "weishu/theme/info.do";
                 HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                     @Override
                     public void onSuccess(final String data) {
                         final CommonModel commonModel = GsonTools.getCommonModel(data);
                         if (commonModel.getFlag().equals("1")){
                             runOnUiThread(new Runnable() {
                                 @Override
                                 public void run() {
                                     WeiShuInfoDetailModel langInfoModel = GsonTools.getWeiShuInfo(data);
                                     if (CommonUtils.isLogin() == true && langInfoModel.getUserid().equals(CustomApplication.loginModel.getUid())){
                                         Intent intent = new Intent(MainActivity.this, WZTActivity.class);
                                         Bundle bundle=new Bundle();
                                         bundle.putSerializable("model", langInfoModel);//序列化
                                         intent.putExtras(bundle);//发送数据
                                         intent.putExtra("selectIndex",selectIndex);
                                         startActivity(intent);
                                     }else {
                                         WZTUtils.goToWZT(MainActivity.this, langInfoModel);
                                     }
                                 }
                             });
                         }else {
                             runOnUiThread(new Runnable() {
                                 @Override
                                 public void run() {
                                     CustomApplication.showTip(commonModel, MainActivity.this);
                                 }
                             });
                         }
                     }

                     @Override
                     public void onError(String msg) {

                     }
                 });
             }
         }).start();

    }

    /**********************以上导航相关************************/


    static class MyHandler extends Handler {

        WeakReference<MainActivity> mWeakReference;
        public MyHandler(MainActivity activity)
        {
            mWeakReference=new WeakReference<MainActivity>(activity);
        }

         //子类重写次方法，处理消息

         @Override
         public void handleMessage(Message msg) {
             super.handleMessage(msg);

             if(mWeakReference == null){
                 return;
             }
             final MainActivity activity = mWeakReference.get();
             if (activity == null){
                 return;
             }

             try {
                 if (msg == null || msg.obj == null || msg.obj.toString() == null){
                     return;
                 }
                 if (msg.obj.toString().equals(HandlerDefine.login_msg)){

                     SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.GetMyInfoKey, 0);//清零更新个人信息

                     if (activity.gesture_layout.getVisibility() == View.VISIBLE){
                         //取消手势
                         SPManageUtils.getInstance(CustomApplication.mContext).putSPString(LetterConstant.GestureKey+CustomApplication.loginModel.getUid(),"");
                         activity.gesture_layout.setVisibility(View.GONE);
                     }

                     /*
                     if (activity.homeLangFragment != null){
                         activity.homeLangFragment.updateAfterLogin();
                     }
                     */

                     if (activity.homeFragment != null){
                         activity.homeFragment.updateAfterLogin();
                     }

                     if (activity.simpleHomePageFragment != null){
                         activity.simpleHomePageFragment.updateAfterLogin();
                     }

                     if (activity.meFragment != null){
                         activity.meFragment.updateUserinfo();
                     }
                     long count = NotifydbService.getUnReadCount(CustomApplication.loginModel.getUid());
                     if (count > 0){
                         activity.img_message_count.setVisibility(View.VISIBLE);
                         activity.img_message_count.setText(count+"");
                     }else {
                         activity.img_message_count.setVisibility(View.INVISIBLE);
                     }

                     //activity.bindMobile();//判断是否需要绑定手机号
                     if (activity.msgHomeFragment != null){
                         activity.msgHomeFragment.afterLogin();
                     }

                     uploadJPUSH(1);//上传极光id
                     getUnReadMsg();
                     activity.getHomeMenu(false);//重新登录后获取菜单


                 new Thread() {
                     @Override
                     public void run() {
                         super.run();
                         //初始化微博
                         activity.initWeiBo();
                         //初始化高德地图
                         CustomApplication.customApplication.initLocation();
                     }
                 }.start();

                 }else if (msg.obj.toString().equals(HandlerDefine.logout_msg)){

                     //2018年11月10日屏蔽
                     //RongIMClient.getInstance().disconnect();
                     if (!CommonUtils.isEmpty(CustomApplication.loginModel.getToken())){
                         CustomApplication.isSign = false;
                         CustomApplication.loginModel.setToken(null);
                         LogindbService.deleteLoginModel();
                     }
                     activity.img_message_count.setVisibility(View.INVISIBLE);

                     //返回首页
                     activity.ResetTabsImg();
                     activity.SetTabsSelectedImg(0);

                 /*
                 Intent intent = new Intent(CustomApplication.mContext, MainActivity.class);
                 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                 startActivity(intent);
                 */
                 }else if (msg.obj.toString().equals(HandlerDefine.showpaymsg)){
                     PayDialog payDialog = new PayDialog(activity);
                     payDialog.show();
                 }else if (msg.obj.toString().equals(HandlerDefine.notify_msg)){
                     long count = 0;
                     if (CommonUtils.isLogin() == true){
                         count = NotifydbService.getUnReadCount(CustomApplication.loginModel.getUid());
                     }
                     if (count > 0){
                         activity.img_message_count.setVisibility(View.VISIBLE);
                         activity.img_message_count.setText(count+"");
                     }else {
                         activity.img_message_count.setVisibility(View.INVISIBLE);
                     }
                     if (activity.msgHomeFragment != null){
                         activity.msgHomeFragment.getLatest();
                     }
                 }else if (msg.obj.toString().equals(HandlerDefine.showmymsg)){
                     if (activity.meFragment != null){
                         activity.ResetTabsImg();
                         activity.SetTabsSelectedImg(3);
                         activity.meFragment.stFragment(msg.what);
                     }
                 }else if (msg.obj.toString().equals(HandlerDefine.updatemsgcountmsg)){
                     long count = 0;
                     if (CommonUtils.isLogin() == true){
                         count = NotifydbService.getUnReadCount(CustomApplication.loginModel.getUid());
                         if(LetterdbService.getAllUnReadCount(CustomApplication.loginModel.getUid()) > 0){
                             count += 1;
                             activity.msgHomeFragment.updateSXTip(1);
                         }else {
                             activity.msgHomeFragment.updateSXTip(0);
                         }
                     }

                     if (count > 0){
                         activity.img_message_count.setVisibility(View.VISIBLE);
                         activity.img_message_count.setText(count+"");
                     }else {
                         activity.img_message_count.setVisibility(View.INVISIBLE);
                     }
                 }else if (msg.obj.toString().equals(HandlerDefine.addcaremsg)){
                     /*
                     if (activity.homeLangFragment != null){
                         activity.homeLangFragment.setFragmentOfIndex(2);
                     }
                     */

                     if (activity.homeFragment != null){
                         activity.homeFragment.setFragmentOfIndex(2);
                     }

                 }else if (msg.obj.toString().equals(HandlerDefine.weibosharemsg)){
                     if (CustomApplication.shareHandler != null){
                         if (CommonUtils.isEmpty(CustomApplication.WbShareActionUrl)){
                             activity.sendMessageToWb(true,CustomApplication.wbHasImage);
                         }else {
                             activity.shareWebToWeiBo();
                         }
                     }
                 }else if (msg.obj.toString().equals(HandlerDefine.publishsignmsg)){
                     Intent intent = new Intent(activity, LangPublishActivity.class);
                     intent.putExtra("signtext",activity.signtext);
                     intent.putExtra("titlename","生活分享");
                     intent.putExtra("tipname","分享新鲜事");
                     activity.startActivityForResult(intent, REQUEST_PUBLISH);
                     new Thread(){
                         @Override
                         public void run() {
                             super.run();
                             activity.getLangName(false);
                         }
                     }.start();
                 }else if (msg.obj.toString().equals(HandlerDefine.carelangupdatemsg)){
                     /*
                     if (activity.homeLangFragment != null){
                         activity.homeLangFragment.updateCareLangTip();
                     }
                     */

                     if (activity.homeFragment != null){
                         activity.homeFragment.updateCareTip(true);
                     }

                     if (activity.simpleHomePageFragment != null){
                         activity.simpleHomePageFragment.updateCareTip(true);
                     }
                 }else if (msg.obj.toString().equals(HandlerDefine.readnotifymsg)){
                     if (!CommonUtils.isEmpty(activity.readNotify)){
                         ToastUtil.show(CustomApplication.mContext,activity.readNotify);
                     }
                 }else if (msg.obj.toString().equals(HandlerDefine.readtimeupdatemsg)){
                     if (activity.meFragment != null){
                         activity.meFragment.updateReadTimeText();
                     }
                 }else if (msg.obj.toString().equals(HandlerDefine.wztnotifymsg)){
                     if (activity.wztId > 0){//跳转到内容发布页面
                         activity.dealWithWZT(activity.wztId+"",0);
                     }
                 }else if (msg.obj.toString().equals(HandlerDefine.publishnotifymsg)){
                     if (activity.meFragment != null){
                         activity.ResetTabsImg();
                         activity.SetTabsSelectedImg(3);
                         activity.meFragment.updateMyLang();
                     }
                     if (msg.what == 1){
                         activity.startTimer();
                     }
                 }else if (msg.obj.toString().equals(HandlerDefine.wjautopublishmsg)){
                     activity.startTimer();
                 }else if (msg.obj.toString().equals((HandlerDefine.wztstartpublishnotifymsg))){
                     activity.startTimer();
                 }else if (msg.obj.toString().equals((HandlerDefine.wztdeletemsg))){
                     if (activity.meFragment != null){
                         activity.ResetTabsImg();
                         activity.SetTabsSelectedImg(3);
                         activity.meFragment.updateMyWZT();
                     }
                 }
             }catch (Exception e){
                 LangPublishActivity.uploadError("MainActivity报错："+CommonUtils.formatString(e.getMessage()));
             }
         }
     }
    /**
     * 广播接收者
     * @author Gordon
     */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            Log.e("TAG","onReceive接收到广播了=" +action + "\n");

            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {    //屏幕关闭启动1像素Activity
                Intent it = new Intent(context, OnePiexlActivity.class);
                it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(it);
            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {   //屏幕打开 结束1像素
                context.sendBroadcast(new Intent("finish"));
                Intent main = new Intent(Intent.ACTION_MAIN);
                main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                main.addCategory(Intent.CATEGORY_HOME);
                context.startActivity(main);
            }else if (action.equals(BroadcastDefine.Login_Success_Action)){
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.login_msg);
                myHandler.sendMessage(msg);
                //myHandler.sendMessageDelayed(msg,500);
                //new getImageCacheAsyncTask(GameActivity.this).execute(CustomApplication.loginModel.getThumbheader());
            }else if (action.equals(BroadcastDefine.Logout_Success_Action)) {//退出登录
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.logout_msg);
                myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.Show_Pay_Action)){
                Log.e("TAG","接收到广播了~");
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.showpaymsg);
                myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.Notify_Msg)){
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.notify_msg);
                myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.Show_My_Action)){
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.showmymsg);
                msg.what = intent.getIntExtra("index",0);
                myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.Update_MsgCount_Action)){
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.updatemsgcountmsg);
                myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.Add_Care_Action)){
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.addcaremsg);
                myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.WeiBo_Share_Action)){
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.weibosharemsg);
                myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.Publish_Sign_Action)){
                signtext = intent.getStringExtra("signtext");
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.publishsignmsg);
                myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.CareLang_Update_Action)){
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.carelangupdatemsg);
                myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.ReadTime_Update_Action)){
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.readtimeupdatemsg);
                myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.Read_Notify_Action)){
                readNotify = intent.getStringExtra("readNotify");
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.readnotifymsg);
                myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.WZTContentStartPublish_Notify_Action)){
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.wztstartpublishnotifymsg);
                myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.WZT_Delete_Notify_Action)){
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.wztdeletemsg);
                myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.WJ_AUTO_PUBLISH_Action)){
                Message msg = new Message();
                msg.obj = new String(HandlerDefine.wjautopublishmsg);
                myHandler.sendMessage(msg);
            }
        }
    };
    /**
     * 注册广播
     * @author Gordon
     */
    public void registerBoradcastReceiver(){
        if (!mReceiverTag) {     //在注册广播接受者的时候 判断是否已被注册,避免重复多次注册广播
            IntentFilter myIntentFilter = new IntentFilter();
            mReceiverTag = true;    //标识值 赋值为 true 表示广播已被注册
            //添加接收广播类型
            myIntentFilter.addAction(BroadcastDefine.Login_Success_Action);
            myIntentFilter.addAction(BroadcastDefine.Logout_Success_Action);
            myIntentFilter.addAction(BroadcastDefine.Show_Pay_Action);
            myIntentFilter.addAction(BroadcastDefine.Notify_Msg);
            myIntentFilter.addAction(BroadcastDefine.Show_My_Action);
            myIntentFilter.addAction(BroadcastDefine.Update_MsgCount_Action);
            myIntentFilter.addAction(BroadcastDefine.Add_Care_Action);
            myIntentFilter.addAction(BroadcastDefine.WeiBo_Share_Action);
            myIntentFilter.addAction(BroadcastDefine.Publish_Sign_Action);
            myIntentFilter.addAction(BroadcastDefine.CareLang_Update_Action);

            myIntentFilter.addAction(BroadcastDefine.Read_Notify_Action);
            myIntentFilter.addAction(BroadcastDefine.ReadTime_Update_Action);
            myIntentFilter.addAction(BroadcastDefine.WZTContentStartPublish_Notify_Action);
            myIntentFilter.addAction(BroadcastDefine.WZT_Delete_Notify_Action);
            myIntentFilter.addAction(BroadcastDefine.WJ_AUTO_PUBLISH_Action);


            /*
            //进程保活相关
            myIntentFilter.addAction("android.intent.action.SCREEN_OFF");
            myIntentFilter.addAction("android.intent.action.SCREEN_ON");
            myIntentFilter.addAction("android.intent.action.USER_PRESENT");
            */

            //注册广播
            registerReceiver(mBroadcastReceiver, myIntentFilter);
        }
    }

     //PayDialog.NetEvevt
     //面对面对战
     @Override
     public void onTextFinish(String text) {
         if (fragments == null || fragments.size() == 0){
             return;
         }
         GameFragment gameFragment = (GameFragment)fragments.get(0);
         gameFragment.pkMenuPopWindow.code = text;
        Intent intent = new Intent(MainActivity.this, PrePKActivity.class);
        Bundle bundle=new Bundle();
        bundle.putSerializable("pkuser", gameFragment.pkMenuPopWindow.pkUserModel);//序列化
        intent.putExtras(bundle);//发送数据
        intent.putExtra("fee",gameFragment.pkMenuPopWindow.mPKMenuModel.getGoldcount());
        intent.putExtra("type",gameFragment.pkMenuPopWindow.mPKMenuModel.getType());
        intent.putExtra("code", CommonUtils.formatString(gameFragment.pkMenuPopWindow.code));
        startActivity(intent);

     }

    /***************************************微博分享相关*****************************************/
    private void initWeiBo() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (CustomApplication.shareHandler == null){//防止重复初始化
                    if (AppUtils.getInstance().isUserAgreeStatus() == true){//用户同意后再初始化
                        WbSdk.install(MainActivity.this,new AuthInfo(MainActivity.this, WeiBoConstant.APP_KEY,WeiBoConstant.REDIRECT_URL, WeiBoConstant.SCOPE));//创建微博API接口类对象
                        CustomApplication.shareHandler = new WbShareHandler(MainActivity.this);
                        CustomApplication.shareHandler.registerApp();
                    }
                }
            }
        });

    }

    @Override
    public void onWbShareSuccess() {
        ToastUtil.show(MainActivity.this,"分享成功");
        Log.e("TAG","分享成功");
        dealWithShareResult();
    }

    @Override
    public void onWbShareCancel() {
        ToastUtil.show(MainActivity.this,"分享取消");
        Log.e("TAG","分享取消");
    }

    @Override
    public void onWbShareFail() {
        ToastUtil.show(MainActivity.this,"分享失败");
        Log.e("TAG","分享失败");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        Log.e("TAG","onNewIntent");
        int action = intent.getIntExtra(AppUtils.KEY_HOME_ACTION, 0);
        if (action == AppUtils.ACTION_RESTART_APP){
            //应用进程已经被系统回收，重新启动应用
            //Toast.makeText(getApplicationContext(),"应用被回收重启走流程",Toast.LENGTH_LONG).show();
            startActivity(new Intent(this, SplashActivity.class));
            finish();
            return;
        }else if (action == AppUtils.ACTION_LOGOUT){
            img_message_count.setVisibility(View.INVISIBLE);
            //返回首页
            ResetTabsImg();
            SetTabsSelectedImg(0);
        }else {
            if (CustomApplication.shareHandler != null && intent != null){
                CustomApplication.shareHandler.doResultIntent(intent,this);
            }
        }
        initPublishHandler();
        goToUrl();

    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     */
    private void sendMessageToWb(boolean hasText, boolean hasImage) {
        sendMultiMessage(hasText, hasImage);
    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     */
    private void sendMultiMessage(boolean hasText, boolean hasImage) {

        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        if (hasText) {
            weiboMessage.textObject = getTextObj();
        }
        if (hasImage) {
            weiboMessage.imageObject = getImageObj(this);
        }
        CustomApplication.wbHasImage = false;
        CustomApplication.shareHandler.shareMessage(weiboMessage, false);
    }

    //网页信息
    private void shareWebToWeiBo(){
        Log.e("TAG","分享网页");
        WebpageObject webpageObject = new WebpageObject(); //分享网页是这个
        Bitmap thumb = BitmapFactory.decodeResource(this.getResources(), R.mipmap.icon);
        webpageObject.setThumbImage(thumb); //注意，它会按照jpeg做85%的压缩，压缩后的大小不能超过32K
        webpageObject.title = CustomApplication.WbShareTitle;//不能超过512
        webpageObject.actionUrl = CustomApplication.WbShareActionUrl;// 不能超过512
        webpageObject.description = CustomApplication.WbShareText;//不能超过1024
        webpageObject.identify = UUID.randomUUID().toString();//这个不知道做啥的
        webpageObject.defaultText = CustomApplication.WbShareText;//"Webpage 默认文案";//这个也不知道做啥的
//上面这些，一条都不能少，不然就会出现分享失败，主要是接口调用失败，而不会通过activity返回错误的intent

//下面这个，就是用户在分享网页的时候，自定义的微博内容
        TextObject textObject = new TextObject();
        textObject.text = CustomApplication.WbShareText;

        WeiboMultiMessage msg = new WeiboMultiMessage();
        msg.mediaObject = webpageObject;
        msg.textObject = textObject;

        CustomApplication.shareHandler.shareMessage(msg, false);
        CustomApplication.WbShareActionUrl = "";//清空链接
    }

    /**
     * 创建文本消息对象。
     * @return 文本消息对象。
     */
    private TextObject getTextObj() {
        TextObject textObject = new TextObject();
        textObject.text = CustomApplication.WbShareText;//"这里是分享的内容";
        textObject.title = CustomApplication.WbShareTitle;//"xxxx";
        textObject.actionUrl = CustomApplication.WbShareActionUrl;//"http://www.baidu.com";
        return textObject;
    }

    /**
     * 创建图片消息对象。
     * @return 图片消息对象。
     */
    private ImageObject getImageObj(Context context) {
        ImageObject imageObject = new ImageObject();
        if (CustomApplication.wbShareBitmap != null){
            imageObject.setThumbImage(CommonUtils.getZoomImage(CustomApplication.wbShareBitmap,24));//缩略图
            imageObject.setImageObject(CommonUtils.getZoomImage(CustomApplication.wbShareBitmap,2048));//大图
        }else {
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon);
            imageObject.setImageObject(bitmap);
        }
        return imageObject;
    }

    //上传分享结果
    private void dealWithShareResult(){
        if (CustomApplication.WbShareType == 1){
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put("id", CustomApplication.WbShareSourceId);
            String url = "miniapp/"+"langappid"+"/sharelanginfo.do";
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(final String data) {
                }

                @Override
                public void onError(String msg) {
                }
            });
        }else if (CustomApplication.WbShareType == 4){//微纸条内容
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put("id", CustomApplication.WbShareSourceId);
            String url = "weishu/content/share.do";
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(final String data) {
                }

                @Override
                public void onError(String msg) {
                }
            });
        }else {
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put("id", CustomApplication.WbShareSourceId);
            String url = "miniapp/"+"langappid"+"/langsharecomment.do";
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(final String data) {
                }

                @Override
                public void onError(String msg) {
                }
            });
        }
    }

    /***************************************微博分享相关*****************************************/


    /***************************************未读（极光）通知相关*****************************************/

    //上传极光id
    public static void uploadJPUSH(final int state){

        new Thread() {
            @Override
            public void run() {
                super.run();
                String jpushid = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.JPUSHRegistrationId,"");
                if (jpushid == null){
                    jpushid = JPushInterface.getRegistrationID(CustomApplication.mContext);
                    if(!CommonUtils.isEmpty(jpushid)){
                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.JPUSHRegistrationId,jpushid);
                    }
                }
                if (CommonUtils.isLogin() == true){
                    final HashMap<String, String> map = new HashMap<String, String>();
                    map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
                    map.put("pushid", jpushid);
                    map.put("state",state+"");
                    map.put("appVersion",BuildConfig.VERSION_NAME);
                    map.put("appBuild", BuildConfig.VERSION_CODE+"");
                    map.put("deviceName",CommonUtils.formatString(DeviceUtils.getDeviceBrand()));
                    map.put("phoneVersion", CommonUtils.formatString(DeviceUtils.getSystemVersion()));
                    map.put("deviceModel",CommonUtils.formatString(DeviceUtils.getSystemModel()));
                    Log.e("TAG","JPUSH上传参数："+map);
                    String url = "miniapp/"+"langappid"+"/uploadpush.do";
                    HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            Log.e("TAG","JPUSH上传结果："+data);
                        }

                        @Override
                        public void onError(String msg) {

                        }
                    });
                }
            }
        }.start();
    }

    //获取微读消息
    public static void getUnReadMsg(){
        if (CommonUtils.isLogin() == true){
            if (isGettingUnRead  == true){
                return;
            }
            isGettingUnRead = true;
            SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.LastGetUnReadMsgTime,(int)(System.currentTimeMillis()/1000));//记录上次获取未读消息的时间
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    final HashMap<String, String> map = new HashMap<String, String>();
                    map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
                    map.put(APIKey.typeKey,"0");
                    String url = "miniapp/"+"langappid"+"/getnewmsg.do";
                    HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            Log.e("TAG","未读消息："+data);
                            isGettingUnRead = false;
                            CommonModel commonModel = GsonTools.getCommonModel(data);
                            if (commonModel.getFlag().equals("1")){
                                List<UserMsgInfoModel> l = GsonTools.getUserMsgInfoModel(data);
                                if (l != null && l.size() > 0){
                                    for (int i = 0; i < l.size(); i++){
                                        UserMsgInfoModel model = l.get(i);
                                        String d = Base64.decode(model.getContent());
                                        Map<String, String> imap = CommonUtils.json2map(d);
                                        if (imap != null){
                                            imap.put("name",CommonUtils.formatString(model.getMsg()));
                                            imap.put("msgType",CommonUtils.formatString(model.getMsgtype()));
                                            //imap.put("time",model.getTime()*1000+"");
                                            dealWithUnReadMsg(imap,model.getTime()*1000);
                                        }
                                    }
                                }else {
                                    SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(AdvertUtils.NewMsgNotifyKey+CustomApplication.loginModel.getUid(), false);
                                }
                            }
                        }

                        @Override
                        public void onError(String msg) {
                             isGettingUnRead = false;
                        }
                    });
                }
            }.start();


        }
    }


    public static void dealWithUnReadMsg(Map<String, String> map, long time){
        if (map == null){
            return;
        }
        String msgname = map.get("msgType");
        Log.e("TAG","解析时间是："+time);

        String dataString = JSONObject.toJSONString(map);
        if (CommonUtils.isEmpty(msgname) || CommonUtils.isEmpty(dataString)){
            return;
        }
        Log.e("TAG","解析内容是："+dataString);
        
        if (msgname.equals(Constant.MessageType.Life_Result)) {//生活圈审核结果
            RCCommandUtils.dealWithLifeResult(dataString,CustomApplication.mContext, time);
        }else if (msgname.equals(Constant.MessageType.LifeLike_Result)) {//生活圈关注
            RCCommandUtils.dealWithCare(dataString,CustomApplication.mContext,time);
        }else if (msgname.equals(Constant.MessageType.LifeDZ_Result)) {//生活圈笔芯信息
            RCCommandUtils.dealWithLife(dataString,Integer.valueOf(Constant.MessageType.LifeDZ_Result),CustomApplication.mContext,time);
        }else if (msgname.equals(Constant.MessageType.LifeC_Result)) {//生活圈评论信息
            RCCommandUtils.dealWithLife(dataString,Integer.valueOf(Constant.MessageType.LifeC_Result),CustomApplication.mContext,time);
        }else if (msgname.equals(Constant.MessageType.LifeCR_Result)) {//生活圈评论回复
            RCCommandUtils.dealWithLife(dataString,Integer.valueOf(Constant.MessageType.LifeCR_Result),CustomApplication.mContext,time);
        }else if (msgname.equals(Constant.MessageType.LifeCL_Result)) {//生活圈评论笔芯
            RCCommandUtils.dealWithLife(dataString,Integer.valueOf(Constant.MessageType.LifeCL_Result),CustomApplication.mContext,time);
        }else if (msgname.equals(Constant.MessageType.LangPrize_Result)) {//生活圈获奖
            RCCommandUtils.dealWithLife(dataString,Integer.valueOf(Constant.MessageType.LangPrize_Result),CustomApplication.mContext,time);
        }else if(msgname.equals(Constant.MessageType.SelfInfo)){//系统通知
            RCCommandUtils.dealWithSystem(dataString,Integer.valueOf(Constant.MessageType.SelfInfo),CustomApplication.mContext,Long.valueOf(time));
        }else if (msgname.equals(Constant.MessageType.Contact_Result)){//用户反馈
            RCCommandUtils.dealWithSystem(dataString,Integer.valueOf(Constant.MessageType.Contact_Result),CustomApplication.mContext,Long.valueOf(time));
        }else if (msgname.equals(Constant.MessageType.Care_Lang_Update)){//关注用户发布了新的微句
            Log.e("TAG","关注用户发布了新的微句");
            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.CareUpdateKey,"1");
            Intent mIntent = new Intent(BroadcastDefine.CareLang_Update_Action);
            //发送广播
            CustomApplication.mContext.sendBroadcast(mIntent);
        }else if (msgname.equals(Constant.MessageType.WeiShu_Like_Notify)) {//微纸条点赞通知
            RCCommandUtils.dealWithWZT(dataString,Integer.valueOf(msgname),CustomApplication.mContext,Long.valueOf(time));
        }else if (msgname.equals(Constant.MessageType.WeiShu_Comment_Notify)) {//微纸条评论通知
            RCCommandUtils.dealWithWZT(dataString,Integer.valueOf(msgname),CustomApplication.mContext,Long.valueOf(time));
        }else if (msgname.equals(Constant.MessageType.WeiShu_Subscribe_Notify)) {//微纸条订阅通知
            RCCommandUtils.dealWithWZT(dataString,Integer.valueOf(msgname),CustomApplication.mContext,Long.valueOf(time));
        }else if (msgname.equals(Constant.MessageType.WeiShu_Content_Notify)) {//微纸条内容点赞、分享、评论、收藏通知
            RCCommandUtils.dealWithWZT(dataString,Integer.valueOf(msgname),CustomApplication.mContext,Long.valueOf(time));
        }else if (msgname.equals(Constant.MessageType.WeiShu_Content_Comment_Notify)) {//微纸条评论点赞、回复、收藏通知
            RCCommandUtils.dealWithWZT(dataString,Integer.valueOf(msgname),CustomApplication.mContext,Long.valueOf(time));
        }else if (msgname.equals(Constant.MessageType.Classify_Request_Notify) || msgname.equals(Constant.MessageType.Classify_Authed_Notify)){
            RCCommandUtils.dealWithClassify(dataString,Integer.valueOf(msgname),CustomApplication.mContext,Long.valueOf(time));
        }else if (msgname.equals(Constant.MessageType.Rank_Smart_Notify)){
            RCCommandUtils.dealWithSmartRank(dataString,Integer.valueOf(msgname),CustomApplication.mContext,Long.valueOf(time));
        }
    }



    /***************************************未读（极光）通知相关*****************************************/

    private void goToUrl(){
        String url = getIntent().getStringExtra(APIKey.urlKey);
        if (!CommonUtils.isEmpty(url)){
            Intent webIntent = new Intent(MainActivity.this, MyWebActivity.class);
            webIntent.putExtra(APIKey.urlKey, url);
            startActivity(webIntent);
        }else {
            lifeResultModel =  (LifeResultModel) getIntent().getSerializableExtra("push");
            if (lifeResultModel != null){
                if (!CommonUtils.isEmpty(lifeResultModel.getMsgType())){
                    if (lifeResultModel.getMsgType().equals(Constant.MessageType.SelfInfo)){
                        if (CommonUtils.isEmpty(lifeResultModel.getType())){
                            return;
                        }
                        //系统通知
                        if (lifeResultModel.getType().equals("0")){
                            //消息通知
                            //文字说明
                            if (!CommonUtils.isEmpty(lifeResultModel.getContent())){
                                final CustomDialog.Builder builder = new CustomDialog.Builder(MainActivity.this);
                                builder.setTitle("系统通知");
                                builder.setMessage(lifeResultModel.getContent());
                                builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                                CustomDialog dialog = builder.create();
                                dialog.show();
                            }
                        }else if (lifeResultModel.getType().equals("1")){
                            //微句推荐
                            //dealWithLang(lifeResultModel.getContent());

                            if (!CommonUtils.isEmpty(lifeResultModel.getDataType()) && lifeResultModel.getDataType().equals("0")){
                                dealWithBestOriginalLang(lifeResultModel.getContent(), 12);
                            }else if (!CommonUtils.isEmpty(lifeResultModel.getDataType()) && lifeResultModel.getDataType().equals("1")){
                                dealWithBestOriginalLang(lifeResultModel.getContent(), 13);
                            }else {
                                //笔芯评论
                                dealWithLang(lifeResultModel.getContent());
                            }

                        }else if (lifeResultModel.getType().equals("3")){
                            //链接推荐
                            Intent webIntent = new Intent(MainActivity.this, MyWebActivity.class);
                            webIntent.putExtra(APIKey.urlKey, lifeResultModel.getContent());
                            startActivity(webIntent);
                        }else if (lifeResultModel.getType().equals("4")){
                            //推荐微纸条
                            dealWithWZT(lifeResultModel.getContent(), 0);
                        }
                    }else if (lifeResultModel.getMsgType().equals(Constant.MessageType.LifeDZ_Result) || lifeResultModel.getMsgType().equals(Constant.MessageType.LifeC_Result)){
                        if (!CommonUtils.isEmpty(lifeResultModel.getDataType()) && lifeResultModel.getDataType().equals("0")){
                            dealWithBestOriginalLang(lifeResultModel.getLifeid(), 12);
                        }else if (!CommonUtils.isEmpty(lifeResultModel.getDataType()) && lifeResultModel.getDataType().equals("1")){
                            dealWithBestOriginalLang(lifeResultModel.getLifeid(), 13);
                        }else {
                            //笔芯评论
                            dealWithLang(lifeResultModel.getLifeid());
                        }
                    }else {
                        //进入消息界面
                        ResetTabsImg();
                        SetTabsSelectedImg(2);
                    }
                }
            }else {

                String langid = getIntent().getStringExtra("langid");
                if (!CommonUtils.isEmpty(langid)){
                    dealWithLang(langid);
                    return;
                }

                int commentCount = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.CommentAppKey,0);
                if (commentCount > 0 && commentCount < 4){
                    SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.CommentAppKey, commentCount+1);
                    //弹出评论
                    final CustomDialog.Builder builder = new CustomDialog.Builder(MainActivity.this);
                    builder.setTitle("温馨提示");
                    builder.setMessage("亲，你使用微句一段时间了，我们期待你的评价和反馈哦~");
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            dialog.dismiss();
                        }
                    });
                    builder.setPositiveButton("马上评价", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.CommentAppKey, 4);
                            dialog.dismiss();
                            try{
                                Uri uri = Uri.parse("market://details?id="+getPackageName());
                                Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            }catch(Exception e){
                                //Toast.makeText(MainActivity.this, "你的手机没有安装Android应用市场", Toast.LENGTH_SHORT).show();
                                e.printStackTrace();
                            }
                        }
                    });
                    CustomDialog dialog = builder.create();
                    dialog.show();
                }
            }
        }
    }

    /*
    private void dealWithWZT(String id, final int selectIndex){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.idKey, id);
        if (CommonUtils.isLogin() == true){
            map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
        }
        String url = "weishu/theme/info.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    WeiShuInfoDetailModel langInfoModel = GsonTools.getWeiShuInfo(data);
                    Intent intent = new Intent(MainActivity.this, WZTActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putSerializable("model", langInfoModel);//序列化
                    intent.putExtras(bundle);//发送数据
                    intent.putExtra("selectIndex",selectIndex);
                    startActivity(intent);
                }else {
                    CustomApplication.showTip(commonModel, MainActivity.this);
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }
    */

    private void dealWithLang(String langid){

        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.idKey, langid);
        if (CommonUtils.isLogin() == true){
            map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
        }
        String url = "miniapp/langappid/getlanginfo.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    LangInfoModel langInfoModel = GsonTools.getLangInfoModel(data);
                    langInfoModel.setIscare(true);
                    if (langInfoModel.getStatus() == 1 || langInfoModel.getStatus() == 4){
                        Intent intent = new Intent(MainActivity.this, LangDetailActivity.class);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("model", langInfoModel);//序列化
                        intent.putExtras(bundle);//发送数据
                        intent.putExtra("latestComment", true);
                        startActivity(intent);
                    }
                }else {
                    CustomApplication.showTip(commonModel, MainActivity.this);
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    private void dealWithBestOriginalLang(String langid, int type){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.idKey, langid);
        map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
        String url = "miniapp/langappid/getlanginfo.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    LangInfoModel langInfoModel = GsonTools.getLangInfoModel(data);

                    langInfoModel.setIscare(true);
                    if (langInfoModel.getStatus() == 1 || langInfoModel.getStatus() == 4){
                        Intent intent = new Intent(MainActivity.this, CommonLangActivity.class);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("model", langInfoModel);//序列化
                        intent.putExtras(bundle);//发送数据
                        intent.putExtra("type", type);
                        startActivity(intent);
                    }else if(langInfoModel.getStatus() == 2 ){
                        Intent intent = new Intent(MainActivity.this, LangPublishActivity.class);
                        if (!CommonUtils.isEmpty(langInfoModel.getImg())){
                            ArrayList<String> l = new ArrayList<String>();
                            List<String> ll = CommonUtils.stringToArrayList(langInfoModel.getImg());
                            l.addAll(ll);
                            intent.putStringArrayListExtra("img", l);
                        }
                        intent.putExtra("isRepublish",true);
                        intent.putExtra("content",langInfoModel.getTitle());
                        intent.putExtra("langid",langInfoModel.getLangid());
                        intent.putExtra("status",langInfoModel.getStatus());
                        intent.putExtra("type",langInfoModel.getType());
                        intent.putExtra("typename",langInfoModel.getTypename());
                        startActivityForResult(intent, REQUEST_PUBLISH);
                    }
                }else {
                    CustomApplication.showTip(commonModel, MainActivity.this);
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }


    //获取广告
    private void getAdv(){
        final HashMap<String, String> map = new HashMap<String, String>();
        if (CommonUtils.isLogin() == true){
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        }else {
            map.put(APIKey.tokenKey, "");
        }
        String url = "miniapp/langappid/getadv.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                final CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    List<AdvModel> list = GsonTools.getAdvModel(data);
                    if (list != null && list.size() > 0){
                        for (AdvModel model : list){
                            if (model.getType() == 0) {//启动广告
                                SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.AdvBgUrl,model.getBgurl());
                                SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(AdvertUtils.AdvStatus,model.isStatus());
                                if (CommonUtils.isEmpty(model.getContenturl())==false) {
                                    SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.AdvContentUrl, model.getContenturl());
                                }
                                loadAdvertImg(model.getBgurl(),AdvertUtils.AdvImgPath);
                            }
                        }

                    }
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    //下载广告loadAdvertImg(model.getBgurl(),AdvertUtils.AdvImgPath);
    //下载图片
    private void loadAdvertImg(final String advertUrl, final String key) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED){
                return;
            }
        }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                    REQUEST_PERMISSION);
            return;
        }

        if (!TextUtils.isEmpty(advertUrl)) {
            final String[] split = advertUrl.split("/");
            File advert = CustomApplication.mContext.getExternalFilesDir("advert");
            //final File file = new File(advert, System.currentTimeMillis() + split[split.length - 1]);
            final File file = new File(advert,  split[split.length - 1]);
            if (AdvertUtils.fileIsExists(file.toString())){
                Log.e("file", "文件存在了："+file.toString());
            }else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("file", "保存路径："+file.toString());
                        try {
                            AdvertUtils.onSaveBitmap(advertUrl, file.toString(),CustomApplication.mContext,key);
                            removeFootList(file.toString(),key);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }).start();
            }

        } else {
            // 获取服务器路径为空时，保存空本地路径，则不显示广告图
            removeFootList("",AdvertUtils.AdvImgPath);
        }

    }

    private void removeFootList(String filePath, String key) {
        String oldFilePath = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(key,"");
        if (!CommonUtils.isEmpty(oldFilePath) && !oldFilePath.equals(filePath)){
            if (AdvertUtils.fileIsExists(oldFilePath)) {
                File f = new File(oldFilePath);
                f.delete();
            }
        }
    }


    //以下是后台微句发布相关
    private void startTimer(){

        if (CommonUtils.isLogin() == false){
            return;
        }

        if (dragImages == null){
            dragImages = new ArrayList<String>();
        }

        if (timerFlag == false) {
            timerFlag = true;
            if (mTimer == null) {
                mTimer = new Timer();
            }
            if (mTimerTask == null) {
                mTimerTask = new TimerTask() {
                    @Override
                    public void run() {
                        sendMessage(1);
                    }
                };
            }
            if(mTimer != null && mTimerTask != null ){
                mTimer.schedule(mTimerTask, delay, period);
            }
        }

    }

    private void stopTimer(){
        if (timerFlag == true){
            timerFlag = false;
            if (mTimer != null) {
                mTimer.cancel();
                mTimer = null;
            }
            if (mTimerTask != null) {
                mTimerTask.cancel();
                mTimerTask = null;
            }
        }
    }

    public void sendMessage(int id){
        if (mHandler != null) {
            Message message = Message.obtain(mHandler, id);
            mHandler.sendMessage(message);
        }
    }

    private void initPublishHandler(){

        if (mHandler != null){
            return;
        }
        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (msg == null){
                    return;
                }
                switch (msg.what) {
                    case 1:

                        if (CommonUtils.isLogin() == false || LangPublishService.getAllPublishCount(CustomApplication.loginModel.getUid()) == 0){
                            stopTimer();
                            isDealWithImg = false;
                            isPublishing = false;
                            isUploading = false;
                            imgIndex = 0;
                            imgString = "";
                            qiniuModel = null;
                            break;
                        }

                        if (isPublishing == false){//取发布内容
                            isPublishing = true;
                            isDealWithImg = true;
                            imgIndex = 0;
                            imgString = "";
                            qiniuModel = null;
                            dragImages.clear();
                            langPublishdbModel = LangPublishService.getOneData(CustomApplication.loginModel.getUid());
                            if (langPublishdbModel == null){
                                stopTimer();
                                isDealWithImg = false;
                                isPublishing = false;
                                isUploading = false;
                                imgIndex = 0;
                                break;
                            }
                            String imgData = langPublishdbModel.getImgdata();
                            if (!CommonUtils.isEmpty(imgData)){
                                List<String> l = CommonUtils.stringToArrayList(imgData);
                                if (l != null && l.size() > 0){
                                    dragImages.addAll(l);
                                }
                            }
                            isDealWithImg = false;
                            break;
                        }

                        if (isGettingQiNiuToken == true){
                            break;
                        }

                        if (qiniuModel == null){
                            getUploadInfo();
                            break;
                        }

                        if (isPublishing == false){
                            break;
                        }

                        if (isDealWithImg == true){
                            break;
                        }

                        if (isUploading == true){
                            break;
                        }
                        isUploading = true;
                        Bitmap bitmap = null;
                        if (dragImages != null && dragImages.size() > 0){
                            for (; imgIndex < dragImages.size(); imgIndex++){
                                if (dragImages.get(imgIndex).contains("http")==false){
                                    if (dragImages.get(imgIndex).contains(Constant.weijuTakePhoto) == true){
                                        bitmap = ImageUtils.getBitmap(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),dragImages.get(imgIndex)));
                                        if (bitmap == null){
                                            bitmap = ImageUtils.getBitmap(dragImages.get(imgIndex));
                                        }
                                    }else {
                                        bitmap = ImageUtils.getBitmap(dragImages.get(imgIndex));
                                    }
                                    System.out.print(imgIndex+"有图片\n");
                                    imgIndex++;
                                    if (bitmap != null){
                                        try{
                                            int W = bitmap.getWidth();
                                            int H = bitmap.getHeight();
                                            if (W > H){
                                                if (W > Constant.imgMaxSize){
                                                    Log.e("TAG", "宽度压缩");
                                                    bitmap = Bitmap.createScaledBitmap(bitmap, Constant.imgMaxSize, Constant.imgMaxSize*H/W, true);
                                                }
                                            }else {
                                                if (H  > Constant.imgMaxSize){
                                                    Log.e("TAG", "高度压缩");
                                                    bitmap = Bitmap.createScaledBitmap(bitmap, Constant.imgMaxSize*W/H, Constant.imgMaxSize, true);
                                                }
                                            }
                                            if (langPublishdbModel != null){
                                                bitmap = FilterTools.toProcessImage(bitmap, langPublishdbModel.getFilter());
                                            }
                                        }catch (Exception e){
                                            LangPublishActivity.uploadError("发布时图片压缩报错："+e.getLocalizedMessage());
                                        }
                                    }
                                    break;
                                }else {
                                    if (imgString.length() >0){
                                        imgString += ",";
                                    }
                                    imgString += dragImages.get(imgIndex);
                                }
                            }
                        }

                        if (bitmap == null){
                            System.out.print("开始发布\n");
                            if (langPublishdbModel != null){
                                if (langPublishdbModel.getDatatype() == 1){//发布微句
                                    uploadLang();
                                }else {//发布微纸条
                                    uploadWZTContent();
                                }
                            }
                           // isUploading = false;
                        }else {
                            System.out.print("开始上传图片\n");
                            uploadImg(bitmap,imgIndex-1);
                        }
                        break;
                    default:
                        break;
                }
            }
        };
    }

    //获取上传图片凭证
    private void getUploadInfo(){
        isGettingQiNiuToken = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                final Map<String,String> map = new HashMap<String, String>();
                map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
                HttpsUtils.getQiniuTokenDo(map, new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            qiniuModel = GsonTools.getQiniuModel(data);
                            if (qiniuModel != null){

                            }
                        }else {
                            LangPublishActivity.uploadError("获取七牛云token失败："+commonModel.getMsg());
                        }
                        isGettingQiNiuToken = false;
                    }

                    @Override
                    public void onError(String msg) {
                        isGettingQiNiuToken = false;
                        LangPublishActivity.uploadError("跟七牛云接口通信失败："+msg);
                    }
                });
            }
        }).start();
    }

    private void updatePublishUI(int dataType){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (dataType == 1){
                    if (meFragment != null){
                        meFragment.updateMyLang();
                    }
                }else {
                    //发送通知
                    Intent mIntent = new Intent(BroadcastDefine.WZTContentPublished_Notify_Action);
                    //发送广播
                    sendBroadcast(mIntent);
                }
            }
        });
    }

    //上传图片
    private void uploadImg(Bitmap bitmap, final int index){
        new Thread(new Runnable() {
            @Override
            public void run() {
                final String name = System.currentTimeMillis()+CustomApplication.loginModel.getUid()+".jpg";
                CommonUtils.uploadBytesToQiniu(qiniuModel.getUploadtoken(), qiniuModel.getUploadurl(), name, CommonUtils.bitmapToBytes(bitmap), new QiniuCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        if (CommonUtils.isEmpty(data)){
                            LangPublishActivity.uploadError("发布失败，把图片删除再试试~");
                            isDealWithImg = false;
                            isPublishing = false;
                            isUploading = false;
                            imgIndex = 0;
                            deleteTempFile();
                            if (langPublishdbModel != null){
                                LangPublishService.deleteById(langPublishdbModel.getId());
                                updatePublishUI(langPublishdbModel.getDatatype());
                            }
                            langPublishdbModel = null;
                        }else {
                            if (imgString.length() >0){
                                imgString += ",";
                            }
                            imgString += data;
                            isUploading = false;
                        }
                    }

                    @Override
                    public void onModelSuccess(QiniuUploadModel data) {

                    }

                    @Override
                    public void onError(String msg) {
                        LangPublishActivity.uploadError("上传图片错误信息："+CommonUtils.formatString(msg));
                        isDealWithImg = false;
                        isPublishing = false;
                        isUploading = false;
                        imgIndex = 0;
                        deleteTempFile();
                        if (langPublishdbModel != null){
                            LangPublishService.deleteById(langPublishdbModel.getId());
                            updatePublishUI(langPublishdbModel.getDatatype());
                        }
                        langPublishdbModel = null;
                    }
                });
            }
        }).start();
    }

    //上传内容
    private void uploadLang(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String publishData = langPublishdbModel.getData();
                if (CommonUtils.isEmpty(publishData)){
                    isDealWithImg = false;
                    isPublishing = false;
                    isUploading = false;
                    imgIndex = 0;
                    if (langPublishdbModel != null){
                        LangPublishService.deleteById(langPublishdbModel.getId());
                        updatePublishUI(langPublishdbModel.getDatatype());
                    }
                    langPublishdbModel = null;
                    return;
                }

                final JsonMap<String, String> map = JsonMap.fromJson(publishData);
                map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
                map.put("img",imgString);
                String url = "miniapp/langappid/publishlang.do";
                if (map.containsKey(APIKey.idKey)){
                    url = "miniapp/langappid/editlang.do";
                }
                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                    @Override
                    public void onSuccess(final String data) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CommonModel commonModel = GsonTools.getCommonModel(data);
                                if (commonModel.getFlag().equals("1")){
                                    deleteTempFile();
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            isDealWithImg = false;
                                            isPublishing = false;
                                            isUploading = false;
                                            imgIndex = 0;
                                            if (langPublishdbModel != null){
                                                LangPublishService.deleteById(langPublishdbModel.getId());
                                            }
                                            langPublishdbModel = null;
                                            if (meFragment != null){
                                                meFragment.updateMyLang();
                                            }
                                        }
                                    });
                                }
                            }
                        });

                    }

                    @Override
                    public void onError(String msg) {
                        deleteTempFile();
                        isDealWithImg = false;
                        isPublishing = false;
                        isUploading = false;
                        imgIndex = 0;
                        if (langPublishdbModel != null){
                            LangPublishService.deleteById(langPublishdbModel.getId());
                            updatePublishUI(langPublishdbModel.getDatatype());
                        }
                        langPublishdbModel = null;
                    }
                });
            }
        }).start();
    }

    //删除临时文件
    private void deleteTempFile(){
        /*
        if (dragImages != null && dragImages.size() > 0){//删除发布过程中生成的图片
            imgIndex = 0;
            for (;imgIndex < dragImages.size(); imgIndex++){
                if (dragImages.get(imgIndex).contains("http")==false){
                    Bitmap bitmap = ImageUtils.getBitmap(dragImages.get(imgIndex));
                    if (bitmap != null){
                        if (CommonUtils.deleteFileByPath(dragImages.get(imgIndex))==true){
                            Log.e("TAG","发布完成文件删除成功:"+dragImages.get(imgIndex));
                        }
                    }
                }
            }
        }
        */
    }

    //上传内容
    private void uploadWZTContent(){


        new Thread(new Runnable() {
            @Override
            public void run() {
                String publishData = langPublishdbModel.getData();
                if (CommonUtils.isEmpty(publishData)){
                    isDealWithImg = false;
                    isPublishing = false;
                    isUploading = false;
                    imgIndex = 0;
                    if (langPublishdbModel != null){
                        LangPublishService.deleteById(langPublishdbModel.getId());
                        updatePublishUI(langPublishdbModel.getDatatype());
                    }
                    langPublishdbModel = null;
                    return;
                }

                final JsonMap<String, String> map = JsonMap.fromJson(publishData);
                map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
                map.put("img",imgString);
                String url = "weishu/content/publish.do";
                if (map.containsKey("langid") == true){
                    url = "weishu/content/edit.do";
                }
                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                    @Override
                    public void onSuccess(final String data) {
                        Log.e("TAG", "发布结果："+data);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CommonModel commonModel = GsonTools.getCommonModel(data);
                                if (commonModel.getFlag().equals("1")){

                                }
                                deleteTempFile();
                                isDealWithImg = false;
                                isPublishing = false;
                                isUploading = false;
                                imgIndex = 0;
                                if (langPublishdbModel != null){
                                    LangPublishService.deleteById(langPublishdbModel.getId());
                                }
                                langPublishdbModel = null;
                                //发送通知
                                Intent mIntent = new Intent(BroadcastDefine.WZTContentPublished_Notify_Action);
                                //发送广播
                                sendBroadcast(mIntent);
                            }
                        });

                    }

                    @Override
                    public void onError(String msg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                deleteTempFile();
                                isDealWithImg = false;
                                isPublishing = false;
                                isUploading = false;
                                imgIndex = 0;
                                if (langPublishdbModel != null){
                                    LangPublishService.deleteById(langPublishdbModel.getId());
                                    updatePublishUI(langPublishdbModel.getDatatype());
                                }
                                langPublishdbModel = null;
                            }
                        });
                    }
                });
            }
        }).start();

    }

    //绑定手机号
    private boolean bindMobile(){
        if (CommonUtils.isLogin() == true){
            if (!CommonUtils.isEmpty(CustomApplication.loginModel.getNeed()) && CustomApplication.loginModel.getNeed().equals("1")){
                if (CommonUtils.isEmpty(CustomApplication.loginModel.getMobile())){
                    Intent intent = new Intent(MainActivity.this, BDThirdActivity.class);
                    startActivity(intent);
                    return true;
                }
            }
        }
        return false;
    }

    //获取绑定信息
    private void getbindInfo(){

        if (CommonUtils.isLogin() == false){
            return;
        }

        if (!CommonUtils.isEmpty(CustomApplication.loginModel.getMobile())){
            return;
        }

        final Map<String, String> map = new HashMap<>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        HttpsUtils.getbindDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    BindInfoModel bindInfoModel = GsonTools.getBindInfoModel(data);
                    CustomApplication.loginModel.setMobile(bindInfoModel.getMobile());
                    CustomApplication.loginModel.setNeed(bindInfoModel.getNeed());
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

}
